std-function
Destroy an initialized value in place
Destroying a value is different from releasing its storage. drop_in_place invokes destruction without transferring the value elsewhere. Prevent any later use or second destructor call for that value. MaybeUninit storage does not automatically drop its contained value. Expected stdout (not executed): drops=1 Common mistake: Calling drop_in_place and then assume_init on the destroyed object.
Formal Syntax & Structure
rust syntaxrust
unsafe { std::ptr::drop_in_place(ptr) }Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::{cell::Cell, mem::MaybeUninit}; struct CountDrop<'a>(&'a Cell<u32>); impl Drop for CountDrop<'_> { fn drop(&mut self) { self.0.set(self.0.get() + 1); } } let count = Cell::new(0); let mut slot = MaybeUninit::new(CountDrop(&count)); // SAFETY: slot contains a valid object, pointer aligned and exclusive; no later use/drop of object. unsafe { std::ptr::drop_in_place(slot.as_mut_ptr()); } println!("drops={}", count.get());}