BorrowCheck › Rust language core
Drop, RAII, drop order
The Drop trait, drop order, drop flags, mem::forget and leaks, ManuallyDrop, dropck.
The topic explains the Drop trait and the RAII idiom: a resource is released by a destructor when its owner goes out of scope. The questions on the Drop trait check which types it can be implemented for (E0120, E0367), why a destructor cannot move a field out of self (E0507), how fields and trait objects are dropped, what needs_drop reports, and how a guard fires on an early return. The drop order subtopic covers fields, function parameters, pattern bindings, Vec elements, static values, temporaries in a match scrutinee and in a block's tail expression, and the cases where the order is unspecified. Drop flags show how the compiler tracks conditional initialization, moves in branches and loops, and partial moves; the subtopic on mem::forget, ManuallyDrop and Box::leak explains why leaking is safe in Rust and what happens to a forgotten Drain. The last subtopic is about the drop check (dropck): why a destructor requires borrowed data to outlive it (E0597), why declaration order decides the outcome, and why Vec<&T> passes the check thanks to #[may_dangle]. The topic builds on ownership and moves and prepares for unsafe code.
48 questions: 21 basic, 22 intermediate, 5 advanced. 5 info pages, 14 sources.
Subtopics
- The
Droptrait and RAII - Drop order
- Drop flags
mem::forget, leaks,ManuallyDrop- Drop check (dropck)
Previous: Smart pointers, interior mutability · Next: Concurrency