How Drop clear memory

Might I also add, that you shouldn't confuse these two:

An example:

fn main() {
    struct Foo(pub usize);
    impl Drop for Foo {
        fn drop(&mut self) {
            println!("Hello, I'm being dropped");
        }
    }
    let x = Foo(0);
} //Look below to see what rust does!

So rust does this (Naively, it's a bit more complicated because 0 is 'static and can be safely reinterpreted):

+ Foo // Call it x //    let x = Foo
Move `0` into x //       let x = Foo(0);
//Scope ends here // }
+ Call <Foo as Drop>::drop(&mut x)
+     println!("Hello, I'm being dropped");
- Allocator "drop" of x

Another example is that of std::mem::drop<T>(_: T):

let x = Foo(0);
drop(x);

turns into (roughly):

//... allocate and initialize x
+ drop(x) //x is now in drop's scope, so the same thing happens as above
- // call <Foo as Drop>::drop(&mut x) and deallocate

Please note, that as mentioned in the docs for std::mem::drop(_)

This function is not magic; it is literally defined as

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