当前位置 : 主页 > 手机开发 > 无线 >

在运行时期间可以移动所有权时,Rust编译器如何知道何时调用drop?

来源:互联网 收集:自由互联 发布时间:2021-06-10
参见英文答案 How does Rust know whether to run the destructor during stack unwind?3个 根据 The Rust Programming Language : In Rust, you can specify that a particular bit of code be run whenever a value goes out of scope, and the
参见英文答案 > How does Rust know whether to run the destructor during stack unwind?                                    3个
根据 The Rust Programming Language

In Rust, you can specify that a particular bit of code be run whenever a value goes out of scope, and the compiler will insert this code automatically

程序员不应该显式释放资源(从Drop trait中调用drop函数),Rust会在所有者超出范围时调用drop,这是在编译期间完成的,但Rust怎么可能知道何时调用如果它取决于运行时信息?

extern crate rand;
use rand::Rng;

struct Foo {}

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

fn main() {
    let foo = Foo {};
    if rand::thread_rng().gen() {
        let _t = foo; // move foo to _t
    } //   1) drop occurs here if random bool is true
} //       2) drop occurs here if random bool is false

在这个代码中,当编译器插入代码释放资源时,drop的调用将放在哪里,放置1)或2)?由于在编译期间无法知道,我认为调用应放在两个地方,但只能调用一个以避免悬空指针.

Rust如何处理这种情况以保证内存安全?

Drop flags:

It turns out that Rust actually tracks whether a type should be dropped or not at runtime. As a variable becomes initialized and uninitialized, a drop flag for that variable is toggled. When a variable might need to be dropped, this flag is evaluated to determine if it should be dropped.

网友评论