Theme
Q024. How are ownership, Drop, and RAII related?
Short Answer
Ownership identifies which value is responsible for a resource. RAII ties that resource's lifetime to the owning value, and Drop defines type-specific cleanup when the value reaches its drop point. Moving the value transfers cleanup responsibility without releasing the resource. Rust then runs custom Drop logic followed by recursive destruction of owned fields.
Deep Dive
RAII means that acquiring a resource produces an initialized owning value. The resource remains managed while that value is alive and is released as part of the value's destruction. This applies to heap allocations, files, sockets, locks, transactions, and other scoped resources.
Most types do not need a custom Drop implementation. A struct automatically owns its fields, and generated destruction recursively drops them. Custom Drop is needed only for additional type-specific behavior, such as closing a raw handle or restoring an external invariant.
Moves preserve RAII: the resource is not released at the source. The destination becomes the owning path that eventually triggers cleanup.
Internal Model
rustc determines drop points from control flow and emits drop glue. For a type implementing Drop, that glue first calls Drop::drop(&mut self) and then recursively destroys the fields that remain initialized.
Cleanup is deterministic on normal control-flow exits and during panic unwinding. It is not guaranteed after process abort, process::exit, deliberate leaks, or suppressed destruction.
Example
rust
struct Session {
name: String,
}
impl Drop for Session {
fn drop(&mut self) {
println!("close {}", self.name);
}
}
fn main() {
let session = Session {
name: String::from("primary"),
};
let active = session;
println!("using {}", active.name);
} // active runs Session::drop, then its String field is droppedCommon Mistakes
- Treating RAII as a mechanism limited to heap memory.
- Assuming a move runs the source value's destructor.
- Implementing
Dropwhen automatic field destruction already performs all required cleanup.
Follow-ups
- In what order does Rust run custom
Dropand field destruction? - Which control-flow exits run destructors?
- Why should unsafe abstractions remain sound if their destructor is forgotten?
Related
- Q005. What does it mean for a value to own a resource?
- Q010. How does ownership determine a value's lifetime?
- Q025. When exactly is a value dropped?
References
- The Rust Programming Language
- Rust Reference
- Rust Standard Library