Sub topic 8
Drop: cleanup when a value goes out of scope
This chapter assumes you know Rust ownership and moves, basic traits, and the difference between stack and heap memory. Here you will see how the Drop trait runs cleanup code and in what order values are dropped.
What Drop does
The Drop trait lets you run code when a value is about to be destroyed. Rust calls it for you when the owner goes out of scope. Box<T> uses it to free its heap memory. Rc<T> uses it to decrease its count. You can use it for any resource: files, sockets, locks.
The trait has one method:
trait Drop {
fn drop(&mut self);
}A first example
This program shows both automatic and early dropping.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let _a = Noisy("a");
let b = Noisy("b");
drop(b);
println!("end of main");
}The output is:
dropping b
end of main
dropping aThe call drop(b) runs the cleanup for b right away. Value _a is dropped when main ends.
Drop order
Rust drops values in a predictable order:
- Local variables are dropped in the reverse order of their creation. The last variable declared is dropped first.
- The fields of a struct are dropped in the order they are declared, after the struct's own
dropmethod runs. - Elements of a
Vecare dropped in order, from first to last.
Dropping early with std::mem::drop
You cannot call value.drop() yourself. Rust rejects it, because the value would be dropped a second time at the end of its scope. That would be a double free.
The function std::mem::drop is in the prelude, so you can write drop(b). It takes the value by move. The value is then owned by drop, which ends immediately, so the destructor runs once. Afterward the compiler stops you from using b.
Early dropping is useful when a value holds a resource you want to release before the scope ends. A common case is a lock guard, which you want to release so other code can take the lock.
Common errors
- Using a value after
drop(x). The move makesxinvalid. You get a "borrow of moved value" error. - Expecting
dropto run for a leaked value. If a value is leaked, for example through a reference cycle withRcor withstd::mem::forget, itsdropnever runs. Do not rely onDropfor safety-critical cleanup. - Panicking inside
drop. If a panic happens while another panic is unwinding, the program aborts. Keepdropsimple. - Giving a
Copytype aDropimpl. Rust forbids it. A type cannot be bothCopyandDrop.
Exercise
A function creates let x = Noisy("x"); let y = Noisy("y"); let z = Noisy("z"); and then returns. In what order are the three values dropped, and why?
Show answer
z, then y, then x. Locals are dropped in reverse order of declaration, so the last one created is the first one cleaned up.
Exercise
Why does b.drop() fail to compile, and what should you write instead?
Show answer
An explicit call would let the destructor run again when b goes out of scope, which is a double free. Write drop(b) instead. The function takes b by move, so the destructor runs exactly once.