Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust what happens if you move an object a Box points to?

Tags:

rust

move

In the following code 'Drop' is being called only once:

#[derive(Default)]
struct MyStruct
{
    my_int: i32,
    my_vec: Vec<i32>,
}

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

fn main() {

    {
    let my_box =std::boxed::Box::new(MyStruct::default());

        {
            let my_ref = *my_box;
    

        } // DROP IS CALLED HERE

    } // NOTHING IS CALLED HERE 
}

Does this compiler knows that Box doesn't point to anything anymore so it doesn't call drop on Box, OR it DOES call drop on Box and Box knows there's no longer a MyStruct so it doesn't call drop on it?

like image 401
Zebrafish Avatar asked Dec 22 '25 06:12

Zebrafish


1 Answers

Box is special and allows you to move a value out of it through a dereference operation (*my_box) — no other kind of dereference can be moved (rather than copied) out of.

In order to implement this, the compiler is separately tracking whether the Box contains a valid value (in the same way that it tracks local variables, statically if possible and with drop flags if not), and whether it has heap memory allocated. When the Box actually falls out of scope (or is explicitly dropped), the Box’s owned memory will be deallocated, but the contained value (MyStruct) is dropped only if it knows you didn’t move out of the Box.

This is an exception to the usual rules of the language. It is impossible to implement your own type that behaves like Box here. There are no public APIs that reflect this special feature of Box; it is only visible through use of the dereference operator.

like image 108
Kevin Reid Avatar answered Dec 23 '25 22:12

Kevin Reid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!