Skip to content

Commit cb3aa4c

Browse files
committed
Less unsafe in the array example of MaybeUninit docs
1 parent 71f9384 commit cb3aa4c

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/libcore/mem/maybe_uninit.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,6 @@ use crate::mem::ManuallyDrop;
112112
///
113113
/// ```
114114
/// use std::mem::{self, MaybeUninit};
115-
/// use std::ptr;
116115
///
117116
/// let data = {
118117
/// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
@@ -122,10 +121,13 @@ use crate::mem::ManuallyDrop;
122121
/// MaybeUninit::uninit().assume_init()
123122
/// };
124123
///
125-
/// // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
126-
/// // we have a memory leak, but there is no memory safety issue.
124+
/// // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
125+
/// // assignment instead of `ptr::write` does not cause the old
126+
/// // uninitialized value to be dropped. Also if there is a panic during
127+
/// // this loop, we have a memory leak, but there is no memory safety
128+
/// // issue.
127129
/// for elem in &mut data[..] {
128-
/// unsafe { ptr::write(elem.as_mut_ptr(), vec![42]); }
130+
/// *elem = MaybeUninit::new(vec![42]);
129131
/// }
130132
///
131133
/// // Everything is initialized. Transmute the array to the
@@ -151,7 +153,7 @@ use crate::mem::ManuallyDrop;
151153
/// let mut data_len: usize = 0;
152154
///
153155
/// for elem in &mut data[0..500] {
154-
/// unsafe { ptr::write(elem.as_mut_ptr(), String::from("hello")); }
156+
/// *elem = MaybeUninit::new(String::from("hello"));
155157
/// data_len += 1;
156158
/// }
157159
///

0 commit comments

Comments
 (0)