Function std::ptr::drop_in_place 1.8.0[−][src]
#[lang = "drop_in_place"]pub unsafe fn drop_in_place<T>(to_drop: *mut T) where
T: ?Sized,
Executes the destructor (if any) of the pointed-to value.
This is semantically equivalent to calling ptr::read and discarding
the result, but has the following advantages:
-
It is required to use
drop_in_placeto drop unsized types like trait objects, because they can't be read out onto the stack and dropped normally. -
It is friendlier to the optimizer to do this over
ptr::readwhen dropping manually allocated memory (e.g. when writing Box/Rc/Vec), as the compiler doesn't need to prove that it's sound to elide the copy.
Safety
Behavior is undefined if any of the following conditions are violated:
-
to_dropmust be valid. -
to_dropmust be properly aligned.
Additionally, if T is not Copy, using the pointed-to value after
calling drop_in_place can cause undefined behavior. Note that *to_drop = foo counts as a use because it will cause the the value to be dropped
again. write can be used to overwrite data without causing it to be
dropped.
Examples
Manually remove the last item from a vector:
use std::ptr; use std::rc::Rc; let last = Rc::new(1); let weak = Rc::downgrade(&last); let mut v = vec![Rc::new(0), last]; unsafe { // Without a call `drop_in_place`, the last item would never be dropped, // and the memory it manages would be leaked. ptr::drop_in_place(&mut v[1]); v.set_len(1); } assert_eq!(v, &[0.into()]); // Ensure that the last item was dropped. assert!(weak.upgrade().is_none());Run