Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Rust compiler know when to invoke drop when ownership may be moved during runtime? [duplicate]

According to 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

The programmer should not release a resource(invoke the drop function from the Drop trait) explicitly, Rust will invoke drop whenever the owner goes out of scope, and this is done during compile time, but how is it possible that Rust knows when to invoke drop if it depends on runtime information?

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

In this codes, when complier insert codes to release resource, where will the invocation of drop be put, place 1) or 2)? Since this can not be known during compile time, I think the invocation should be put in both places, but only one can be called to avoid dangling pointer.

How does Rust handle such scenario to guarantee memory safety?

like image 425
user922965 Avatar asked Oct 30 '18 03:10

user922965


1 Answers

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.

like image 123
DK. Avatar answered Nov 15 '22 09:11

DK.