FerrousPath

Level 4 · Expert· Lesson 3 of 9 · 30 min

Drop, drop check and PhantomData

Destructor order, panic safety and leak safety, why a generic Drop makes the borrow checker stricter, and how PhantomData expresses ownership.

Destructors, precisely

When a value goes out of scope, Rust runs its drop glue: first the type’s own Drop::drop, if it has one, then the drop glue of each field in declaration order.

struct Noisy(&'static str);
impl Drop for Noisy {
    fn drop(&mut self) { println!("  drop {}", self.0); }
}

struct Pair { first: Noisy, second: Noisy }
impl Drop for Pair {
    fn drop(&mut self) { println!("  drop Pair (fields are still valid here)"); }
}

fn main() {
    println!("locals: reverse declaration order");
    let _a = Noisy("a");
    let _b = Noisy("b");

    println!("fields: declaration order, after the struct's own drop");
    let _p = Pair { first: Noisy("first"), second: Noisy("second") };

    println!("temporaries: end of the enclosing statement");
    let _len = Noisy("temp").0.len();

    println!("`let _ = ` does not bind: dropped immediately");
    let _ = Noisy("unbound");

    println!("end of main");
}

Facts worth memorising:

  • Locals drop in reverse order; fields, tuple elements and array elements in forward order.
  • Drop::drop takes &mut self, so you cannot move a field out. Use Option::take, ManuallyDrop, or mem::replace.
  • A type cannot be both Copy and Drop.
  • Moving out of a variable cancels its drop; when the move is conditional the compiler tracks it with hidden drop flags.
  • let _ = expr; drops immediately; let _guard = expr; holds until end of scope. Confusing them with a lock guard is a classic bug.

Panic safety

A panic unwinds the stack, running destructors along the way. Unsafe code must therefore keep its invariants intact at every point where a panic could occur — which includes every call to user-supplied code: a closure, Clone::clone, Ord::cmp, Drop::drop.

/// Applies `f` to every element in place. Sound even if `f` panics.
fn map_in_place<T>(v: &mut Vec<T>, mut f: impl FnMut(T) -> T) {
    struct Guard<'a, T> { v: &'a mut Vec<T>, done: usize, len: usize }

    impl<T> Drop for Guard<'_, T> {
        fn drop(&mut self) {
            // If we get here by unwinding, element `done` was moved out and never replaced.
            // Drop the elements after it, then expose only the ones already transformed.
            if self.done < self.len {
                // SAFETY: elements done+1..len are still initialised and are dropped exactly once.
                unsafe {
                    let tail = self.v.as_mut_ptr().add(self.done + 1);
                    std::ptr::slice_from_raw_parts_mut(tail, self.len - self.done - 1).drop_in_place();
                }
            }
            // SAFETY: exactly `done` leading elements are initialised.
            unsafe { self.v.set_len(self.done) };
        }
    }

    let len = v.len();
    // SAFETY: while the loop runs the Vec claims to be empty, so a panic cannot double-drop.
    unsafe { v.set_len(0) };
    let mut g = Guard { v, done: 0, len };
    while g.done < g.len {
        // SAFETY: index is in bounds; the slot is read once and then overwritten.
        unsafe {
            let slot = g.v.as_mut_ptr().add(g.done);
            let new = f(slot.read()); // may panic: the guard cleans up
            slot.write(new);
        }
        g.done += 1;
    }
}

fn main() {
    let mut names = vec![String::from("a"), String::from("b"), String::from("c")];
    map_in_place(&mut names, |s| s + "!");
    println!("{names:?}");

    let result = std::panic::catch_unwind(move || {
        map_in_place(&mut names, |s| if s == "b!" { panic!("boom") } else { s });
    });
    println!("survived a panic without double free: {}", result.is_err());
}

The discipline: before calling foreign code, put the data structure in a state that is safe to drop, and use a guard whose destructor restores or truncates. The standard library’s Vec::retain, drain and sort implementations all follow it. A function that leaves memory safe after a panic is exception safe; whether the data is still meaningful is a weaker, logical concern (that is what mutex poisoning signals).

Leaking is safe

mem::forget, a reference cycle of Rc, or a thread that never ends will all prevent a destructor from running — in entirely safe code. Therefore:

No unsafe code may rely on a destructor running for memory safety.

This was learned painfully just before Rust 1.0 (the “leakpocalypse”): the original scoped-thread API returned a guard that joined the thread on drop, and forgetting the guard let a thread outlive data it borrowed. The modern thread::scope takes a closure, so the join happens in code the user cannot skip. Vec::drain shows the other defence: it sets the vector’s length to zero up front, so if the Drain is leaked the vector merely loses elements rather than exposing moved-out ones.

Drop check

Consider a struct that holds a reference and has a destructor. The destructor might read through that reference, so the referent must strictly outlive the struct:

struct Inspector<'a>(&'a String);

impl Drop for Inspector<'_> {
    fn drop(&mut self) {
        println!("inspector sees: {}", self.0); // uses the borrow during drop
    }
}

fn main() {
    let inspector;
    let text = String::from("data");
    inspector = Inspector(&text); // ❌ error[E0597]: `text` does not live long enough
} // locals drop in reverse order: `text` first, then `inspector` — whose drop would read freed memory

Remove the Drop impl and this compiles: without a destructor, nothing can observe the dangling reference. This analysis is the drop checker. Its rule: if a type has a Drop impl generic over a lifetime or type parameter, the compiler conservatively assumes the destructor may access data of that lifetime or type, so that data must outlive the value.

Swap the two let lines so text is declared first, and it compiles: declaration order fixes the drop order.

The escape hatch: #[may_dangle]

Vec<T>’s destructor drops its Ts but never otherwise reads them. So Vec<&'a str> may safely be dropped after 'a has ended (dropping a reference does nothing). The standard library tells the drop checker this with an unstable, unsafe attribute:

// From the standard library (simplified); `may_dangle` requires nightly.
unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
    fn drop(&mut self) { /* drop each element, free the buffer */ }
}

#[may_dangle] T promises: “my destructor does not access T except to drop it”. And that exception is why PhantomData matters.

PhantomData

A type that manages memory through a raw pointer has no field of type T, so the compiler knows nothing about its relationship to T. PhantomData<T> is a zero-sized field that says “treat me as if I stored a T”:

use std::marker::PhantomData;
use std::ptr::NonNull;

struct MyBox<T> {
    ptr: NonNull<T>,          // covariant, non-null, enables the Option niche
    _owns: PhantomData<T>,    // we own a T: we will drop one
}

impl<T> MyBox<T> {
    fn new(value: T) -> Self {
        let ptr = NonNull::from(Box::leak(Box::new(value)));
        MyBox { ptr, _owns: PhantomData }
    }
}

impl<T> std::ops::Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &T {
        // SAFETY: ptr came from a live Box and we have not freed it.
        unsafe { self.ptr.as_ref() }
    }
}

impl<T> Drop for MyBox<T> {
    fn drop(&mut self) {
        // SAFETY: ptr came from Box::leak and is dropped exactly once.
        unsafe { drop(Box::from_raw(self.ptr.as_ptr())) };
    }
}

// SAFETY: MyBox<T> owns its T uniquely, exactly like Box<T>.
unsafe impl<T: Send> Send for MyBox<T> {}
unsafe impl<T: Sync> Sync for MyBox<T> {}

fn main() {
    let b = MyBox::new(String::from("owned through a raw pointer"));
    println!("{} ({} bytes)", *b, std::mem::size_of::<Option<MyBox<String>>>());
}

PhantomData<T> has three effects:

  1. Variance — the struct is covariant in T (see the previous lesson’s table for alternatives).
  2. Auto traits — Send/Sync are inherited from T. (Here NonNull already removes them, so we add them back with explicit unsafe impls and bounds.)
  3. Drop check — combined with #[may_dangle], it tells the checker that dropping this type drops a T.

Since Rust 1.0 the third point matters only alongside #[may_dangle]: a type with a plain Drop impl is already treated conservatively. But writing PhantomData<T> on any owning raw-pointer type remains the correct, self-documenting habit.

ManuallyDrop

ManuallyDrop<T> wraps a value whose destructor will not run automatically. It is how you move a field out in drop, control drop order explicitly, or hand ownership to raw-pointer code:

use std::mem::ManuallyDrop;

struct Session { log: ManuallyDrop<Vec<String>> }

impl Drop for Session {
    fn drop(&mut self) {
        // SAFETY: `log` is not used again after this; the field's own drop is suppressed.
        let log = unsafe { ManuallyDrop::take(&mut self.log) };
        println!("flushing {} entries by value: {log:?}", log.len());
    }
}

fn main() {
    let _s = Session { log: ManuallyDrop::new(vec!["start".into(), "stop".into()]) };
}

Exercises

  1. Predict the complete output of a program with nested structs, a tuple, a temporary in a match scrutinee, and a let _ =. Then run it.
  2. Write a naive fn map_in_place without the guard, find the double free with Miri by passing a panicking closure under catch_unwind, then add the guard.
  3. Take the Inspector example and make it compile in three ways: reorder the declarations; remove the Drop impl; store an owned String.
  4. Why would this be unsound if leaking were not safe to assume? struct JoinGuard<'a>(…) whose Drop joins a thread borrowing 'a data. Write the exploit in pseudo-code with mem::forget.

Check your understanding

Pick an answer to see the explanation.

  1. 1.In what order are a struct's fields dropped?

  2. 2.Why did std::thread::scoped (pre-1.0) turn out to be unsound?

  3. 3.What does adding PhantomData<T> to a struct holding *mut T tell the compiler?

Key terms in this lesson

Finished the lesson and the exercises?