Puzzling Box drop implementation

โš“ Rust    ๐Ÿ“… 2026-03-22    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 5      

surdeus

This 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

Read full topic

๐Ÿท๏ธ Rust_feed