maybe_uninit.rs - source
Skip to main content core/mem/ maybe_uninit.rs 1 use crate ::any::type_name ; 2 use crate ::clone::TrivialClone ; 3 use crate ::marker::Destruct ; 4 use crate ::mem::{ ManuallyDrop , transmute_neo }; 5 use crate ::{ fmt , intrinsics , ptr , slice }; 6 7 /// A wrapper type to construct uninitialized instances of `T`. 8 /// 9 /// # Initialization invariant 10 /// 11 /// The compiler, in general, assumes that a variable is [properly initialized or "valid"][validity] 12 /// according to the requirements of the variable's type.
For example, a variable of 13 /// reference type must be aligned and non-null. This is an invariant that must 14 /// *always* be upheld, even in unsafe code. As a consequence, zero-initializing a 15 /// variable of reference type causes instantaneous undefined behavior, 16 /// no matter whether that reference ever gets used to access memory: 17 /// 18 /// ```rust,no_run 19 /// # #![allow(invalid_value)] 20 /// use std::mem::{self, MaybeUninit}; 21 /// 22 /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️ 23 /// // The equivalent code with `MaybeUninit<&i32>`: 24 /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️ 25 /// ``` 26 /// 27 /// This is exploited by the compiler for various optimizations, such as eliding 28 /// run-time checks and optimizing `enum` layout.
29 /// 30 /// Similarly, entirely uninitialized memory may have any content, while a `bool` must 31 /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior: 32 /// 33 /// ```rust,no_run 34 /// # #![allow(invalid_value)] 35 /// use std::mem::{self, MaybeUninit}; 36 /// 37 /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️ 38 /// // The equivalent code with `MaybeUninit<bool>`: 39 /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️ 40 /// ``` 41 /// 42 /// Moreover, uninitialized memory is special in that it does not have a fixed value ("fixed" 43 /// meaning "it won't change without being written to").
Reading the same uninitialized byte 44 /// multiple times can give different results. This makes it undefined behavior to have 45 /// uninitialized data in a variable even if that variable has an integer type, which otherwise can 46 /// hold any *fixed* bit pattern: 47 /// 48 /// ```rust,no_run 49 /// # #![allow(invalid_value)] 50 /// use std::mem::{self, MaybeUninit}; 51 /// 52 /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️ 53 /// // The equivalent code with `MaybeUninit<i32>`: 54 /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️ 55 /// ``` 56 /// 57 /// Conversely, sometimes it is okay to not initialize *all* bytes of a `MaybeUninit` 58 /// before calling `assume_init`.
For instance, padding bytes do not have to be initialized. 59 /// See the field-by-field struct initialization example below for a case of that. 60 /// 61 /// On top of that, remember that most types have additional invariants beyond merely 62 /// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`] 63 /// is considered initialized (under the current implementation; this does not constitute 64 /// a stable guarantee) because the only requirement the compiler knows about it 65 /// is that the data pointer must be non-null.
Creating such a `Vec<T>` does not cause 66 /// *immediate* undefined behavior, but will cause undefined behavior with most 67 /// safe operations (including dropping it). 68 /// 69 /// [`Vec<T>`]: ../../std/vec/struct.Vec.html 70 /// 71 /// # Examples 72 /// 73 /// `MaybeUninit<T>` serves to enable unsafe code to deal with uninitialized data. 74 /// It is a signal to the compiler indicating that the data here might *not* 75 /// be initialized: 76 /// 77 /// ```rust 78 /// use std::mem::MaybeUninit; 79 /// 80 /// // Create an explicitly uninitialized reference.
The compiler knows that data inside 81 /// // a `MaybeUninit<T>` may be invalid, and hence this is not UB: 82 /// let mut x = MaybeUninit::<&i32>::uninit(); 83 /// // Set it to a valid value. 84 /// x.write(&0); 85 /// // Extract the initialized data -- this is only allowed *after* properly 86 /// // initializing `x`! 87 /// let x = unsafe { x.assume_init() }; 88 /// ``` 89 /// 90 /// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
91 /// 92 /// You can think of `MaybeUninit<T>` as being a bit like `Option<T>` but without 93 /// any of the run-time tracking and without any of the safety checks. 94 /// 95 /// ## out-pointers 96 /// 97 /// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data 98 /// from a function, pass it a pointer to some (uninitialized) memory to put the 99 /// result into. This can be useful when it is important for the caller to control 100 /// how the memory the result is stored in gets allocated, and you want to avoid 101 /// unnecessary moves.
102 /// 103 /// ``` 104 /// use std::mem::MaybeUninit; 105 /// 106 /// unsafe fn make_vec(out: *mut Vec<i32>) { 107 /// // `write` does not drop the old contents, which is important. 108 /// unsafe { out.write(vec![1, 2, 3]); } 109 /// } 110 /// 111 /// let mut v = MaybeUninit::uninit(); 112 /// unsafe { make_vec(v.as_mut_ptr()); } 113 /// // Now we know `v` is initialized! This also makes sure the vector gets 114 /// // properly dropped.
115 /// let v = unsafe { v.assume_init() }; 116 /// assert_eq!(&v, &[1, 2, 3]); 117 /// ``` 118 /// 119 /// ## Initializing an array element-by-element 120 /// 121 /// `MaybeUninit<T>` can be used to initialize a large array element-by-element: 122 /// 123 /// ``` 124 /// use std::mem::{self, MaybeUninit}; 125 /// 126 /// let data = { 127 /// // Create an uninitialized array of `MaybeUninit`. 128 /// let mut data: [MaybeUninit<Vec<u32>>; 1000] = [const { MaybeUninit::uninit() }; 1000]; 129 /// 130 /// // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, 131 /// // we have a memory leak, but there is no memory safety issue.
132 /// for elem in &mut data[..] { 133 /// elem.write(vec![42]); 134 /// } 135 /// 136 /// // Everything is initialized. Transmute the array to the 137 /// // initialized type. 138 /// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) } 139 /// }; 140 /// 141 /// assert_eq!(&data[0], &[42]); 142 /// ``` 143 /// 144 /// You can also work with partially initialized arrays, which could 145 /// be found in low-level datastructures.
146 /// 147 /// ``` 148 /// use std::mem::MaybeUninit; 149 /// 150 /// // Create an uninitialized array of `MaybeUninit`. 151 /// let mut data: [MaybeUninit<String>; 1000] = [const { MaybeUninit::uninit() }; 1000]; 152 /// // Count the number of elements we have assigned. 153 /// let mut data_len: usize = 0; 154 /// 155 /// for elem in &mut data[0..500] { 156 /// elem.write(String::from("hello")); 157 /// data_len += 1; 158 /// } 159 /// 160 /// // For each item in the array, drop if we allocated it.
161 /// for elem in &mut data[0..data_len] { 162 /// unsafe { elem.assume_init_drop(); } 163 /// } 164 /// ``` 165 /// 166 /// ## Initializing a struct field-by-field 167 /// 168 /// You can use `MaybeUninit<T>` and the [`&raw mut`] syntax to initialize structs field by field: 169 /// 170 /// ```rust 171 /// use std::mem::MaybeUninit; 172 /// 173 /// #[derive(Debug, PartialEq)] 174 /// pub struct Foo { 175 /// name: String, 176 /// list: Vec<u8>, 177 /// } 178 /// 179 /// let foo = { 180 /// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit(); 181 /// let ptr = uninit.as_mut_ptr(); 182 /// 183 /// // Initializing the `name` field 184 /// // Using `write` instead of assignment via `=` to not call `drop` on the 185 /// // old, uninitialized value.
186 /// unsafe { (&raw mut (*ptr).name).write("Bob".to_string()); } 187 /// 188 /// // Initializing the `list` field 189 /// // If there is a panic her
The rest of this page is on the live site.