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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With