5

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?

Cœur
  • 34,719
  • 24
  • 185
  • 251
user922965
  • 125
  • 1
  • 6

1 Answers1

9

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.

DK.
  • 49,288
  • 3
  • 161
  • 146
  • This is plagiarised from the link you provided – WhatsThePoint Nov 16 '18 at 11:21
  • 4
    @WhatsThePoint ... it's called "quoting". It's not plagiarism unless I claimed to have written it, which I didn't. Stack Overflow mods don't like it when you only link to something, rather than including the relevant information (in case the link dies), and there's no point in uselessly re-wording something that's already explained perfectly well. – DK. Nov 16 '18 at 11:24
  • You could've still provided more information in your answer, rather than a direct copy paste job, especially considering this is a duplicate (which you should've closed due to you having the gold badge) – WhatsThePoint Nov 16 '18 at 11:26