Puzzling Box drop implementation
โ Rust ๐ 2026-03-22 ๐ค surdeus ๐๏ธ 5This isnโt important, but I donโt understand Box:drop.
unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
#[inline]
fn drop(&mut self) {
// the T in the Box is dropped by the compiler before the destructor is run
let ptr = self.0;
unsafe {
let layout = Layout::for_value_raw(ptr.as_ptr());
if layout.size() != 0 {
self.1.deallocate(From::from(ptr.cast()), layout);
}
}
}
}
Specifically the comment:
โ// the T in the Box is dropped by the compiler before the destructor is runโ
How does that happen? How does the compiler know?
I used drop_in_place to drop the T, which seems logical.
4 posts - 3 participants
๐ท๏ธ Rust_feed