Theme
Q028. What is drop glue?
Short Answer
Drop glue is compiler-generated destruction code for a type. It calls the type's custom Drop::drop implementation when present and then recursively drops fields that require destruction. Types can therefore need drop glue without implementing Drop themselves. Drop glue follows initialization state and guaranteed field order; it is static code generation, not garbage collection.
Deep Dive
A struct containing String, Vec<T>, or another resource-owning field needs destruction even if the struct has no custom destructor. The compiler generates the recursive calls required to clean up that ownership tree.
Conceptually, destruction of Container performs:
text
Container::drop(&mut self) if implemented
drop field 0 if initialized
drop field 1 if initialized
...For trait objects, the vtable identifies the concrete destructor. Generic code gets appropriate drop behavior after monomorphization. Types with no custom destructor and no fields requiring destruction can have no observable drop work.
Internal Model
After MIR drop elaboration decides which drop sites are live, each remaining drop invokes a drop shim or drop glue for the target type. That glue encodes custom destruction, recursive field destruction, and the required order.
std::mem::needs_drop::<T>() can conservatively report whether dropping T may matter, but it is an optimization aid rather than a safety check.
Example
rust
struct Job {
name: String,
payload: Vec<u8>,
}
fn main() {
let job = Job {
name: String::from("index"),
payload: vec![1, 2, 3],
};
println!("{}: {} bytes", job.name, job.payload.len());
} // generated drop glue destroys both fieldsCommon Mistakes
- Thinking only types with an explicit
impl Droprequire destruction. - Treating drop glue as runtime ownership metadata or a background collector.
- Assuming
Drop::dropis responsible for recursively dropping fields itself.
Follow-ups
- How does drop glue handle trait objects?
- Why can partially moved values require field-specific drop glue?
- What does
std::mem::needs_dropguarantee?
Related
- Q016. What is a partial move?
- Q024. How are ownership,
Drop, and RAII related? - Q029. What are drop flags and why does the compiler need them?
References
- Rust Reference
- Rust Standard Library
- rustc-dev-guide