在 Rust 中是否可以在作用域结束之前删除一个对象? [英] Is it possible in Rust to delete an object before the end of scope?

查看:28
本文介绍了在 Rust 中是否可以在作用域结束之前删除一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在作用域结束时,编译器会自动生成代码以调用析构函数来删除不再需要的对象.

From what I understand, the compiler automatically generates code to call the destructor to delete an object when it's no longer needed, at the end of scope.

在某些情况下,在不再需要对象时立即将其删除是有益的,而不是等待它超出范围.是否可以在 Rust 中显式调用对象的析构函数?

In some situations, it is beneficial to delete an object as soon as it's no longer needed, instead of waiting for it to go out of scope. Is it possible to call the destructor of an object explicitly in Rust?

推荐答案

在 Rust 中是否可以在作用域结束之前删除一个对象?

Is it possible in Rust to delete an object before the end of scope?

是的.

是否可以在 Rust 中显式调用对象的析构函数?

Is it possible to call the destructor of an object explicitly in Rust?

没有

为了澄清,您可以使用 std::mem::drop 转移一个变量的所有权,这会导致它超出范围:

To clarify, you can use std::mem::drop to transfer ownership of a variable, which causes it to go out of scope:

struct Noisy;

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("Dropping Noisy!");
    }
}

fn main() {
    let a = Noisy;
    let b = Noisy;

    println!("1");

    drop(b);

    println!("2");
}

1
Dropping Noisy!
2
Dropping Noisy!

但是,禁止您自己调用析构函数(Drop 特性的实现).这样做会导致双重释放情况,因为编译器仍会插入对 Drop trait 的自动调用.

However, you are forbidden from calling the destructor (the implementation of the Drop trait) yourself. Doing so would lead to double free situations as the compiler will still insert the automatic call to the the Drop trait.

有趣的旁注——drop 的实现非常优雅:

Amusing side note — the implementation of drop is quite elegant:

pub fn drop<T>(_x: T) { }

这篇关于在 Rust 中是否可以在作用域结束之前删除一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆