Rust Reference ยท Smart Pointers and Memory
Rust ManuallyDrop and MaybeUninit
Reference for Rust ManuallyDrop<T> and MaybeUninit<T>: suppress automatic drops, build values piece by piece, assume_init rules and safe array initialization.
Rust normally guarantees that every value is initialized and is dropped exactly once. Two wrapper types let unsafe code take control of those two guarantees. ManuallyDrop<T> stops the compiler from running T's destructor automatically; you decide if and when it runs. MaybeUninit<T> holds memory that may not yet contain a valid T, so you can fill it in gradually.
Both are tools for low-level code: containers, FFI, performance-sensitive initialization. Using them correctly requires unsafe at exactly the points where you promise something the compiler cannot check.
use std::mem::{ManuallyDrop, MaybeUninit}; let keep = ManuallyDrop::new(String::from("never dropped automatically")); let slot: MaybeUninit<u32> = MaybeUninit::uninit();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
#[repr(transparent)] pub struct ManuallyDrop<T: ?Sized> { /* private */ } impl<T> ManuallyDrop<T> { pub const fn new(value: T) -> ManuallyDrop<T>; pub const fn into_inner(slot: ManuallyDrop<T>) -> T; pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T; } impl<T: ?Sized> ManuallyDrop<T> { pub unsafe fn drop(slot: &mut ManuallyDrop<T>); } #[repr(transparent)] pub union MaybeUninit<T> { /* private */ } impl<T> MaybeUninit<T> { pub const fn uninit() -> MaybeUninit<T>; pub const fn zeroed() -> MaybeUninit<T>; pub const fn new(val: T) -> MaybeUninit<T>; pub fn write(&mut self, val: T) -> &mut T; pub const fn as_ptr(&self) -> *const T; pub const fn as_mut_ptr(&mut self) -> *mut T; pub const unsafe fn assume_init(self) -> T; pub const unsafe fn assume_init_ref(&self) -> &T; pub unsafe fn assume_init_drop(&mut self); }
| Item | Description |
|---|---|
ManuallyDrop::new / into_inner |
Wrap a value without a destructor / unwrap it (destructor active again). |
ManuallyDrop::drop |
Runs the destructor in place. Unsafe: calling it twice, or using the value afterwards, is undefined behavior. |
ManuallyDrop::take |
Moves the value out, leaving the wrapper logically empty. Unsafe: do not touch the wrapper afterwards. |
MaybeUninit::uninit() |
Memory with no valid value. |
MaybeUninit::zeroed() |
All bytes zero; valid only if T allows an all-zero pattern. |
write(v) |
Safe: stores v and returns a reference to it. Does not drop old contents. |
assume_init() |
Unsafe: you promise the memory holds a valid T. |
assume_init_drop() |
Unsafe: runs T's destructor in place. |
Edge cases. Dropping a MaybeUninit<T> never drops the T inside, so an initialized String that you forget to take out is leaked (safe but wasteful). Reading uninitialized bytes as an integer is undefined behavior, even for u8. Types such as bool, references, Box, NonZero* and enums have invalid bit patterns that zeroed or partial init can produce.
Usage notes
- Prefer safe alternatives first:
std::array::from_fn,Vec::with_capacity,Option<T>, ormem::take. Reach forMaybeUninitonly when profiling or FFI demands it. - The old
mem::uninitialized()andmem::zeroed()shortcuts are deprecated or dangerous;MaybeUninitreplaced them. ManuallyDropis howVec,Rcand friends hand out their parts without a double drop, and howmem::forgetis conceptually implemented. Seemem::forgeton std::mem.- Wrapping a field in
ManuallyDropin aDropimpl lets you move it out indrop, which is otherwise forbidden. - Panic safety matters: if initialization code can panic halfway, make sure the partly built value is not dropped as if complete.
- Pass
as_mut_ptr()to C functions that fill an out-parameter, then callassume_initonly after checking the return code.
Related
- std::mem, std::ptr, Pin, PhantomData
- Tutorial: MaybeUninit and transmute, Drop and RAII, Unsafe Rust