[The Rust Programming Language] 15. Smart Pointers
15. Smart Pointers
15.3 Running Code on Cleanup with the Drop Trait
The second trait important to the smart pointer pattern is Drop
, which lets you customize what happens when a value is about to go out of scope. You can provide an implementation for the Dro
p` trait on any type, and the code you specify can be used to release resources like files or network connections.
Specify the code to run when a value goes out of scope by implementing the Drop trait. The Drop
trait requires you to implement one method named drop
that takes a mutable reference to self
. To see when Rust calls drop, let’s implement drop with println!
statements for now.
1 | struct CustomSmartPointer { |
When we run this program, we’ll see the following output:
1 | cargo run |
Rust automatically called drop for us when our instances went out of scope, calling the code we specified. Variables are dropped in the reverse order of their creation, so d was dropped before c.
Dropping a Value Early with std::mem::drop
You might want to force the drop method that releases the lock so that other code in the same scope can acquire the lock. Rust doesn’t let you call the Drop trait’s drop method manually; instead you have to call the std::mem::drop
function provided by the standard library if you want to force a value to be dropped before the end of its scope.
Rust doesn’t let us call drop
of Drop trait explicitly because Rust would still automatically call drop on the value at the end of main. This would be a double free error because Rust would be trying to clean up the same value twice.
The std::mem::drop
function is different from the drop method in the Drop trait. We call it by passing the value we want to force to be dropped early as an argument.
1 | struct CustomSmartPointer { |
Running this code will print the following:
1 | cargo run |