]> git.lizzy.rs Git - rust.git/commitdiff
Less unsafe in the array example of MaybeUninit docs
authorAndre Bogus <bogusandre@gmail.com>
Fri, 12 Jul 2019 20:13:48 +0000 (22:13 +0200)
committerAndre Bogus <bogusandre@gmail.com>
Sun, 14 Jul 2019 11:32:14 +0000 (13:32 +0200)
src/libcore/mem/maybe_uninit.rs

index 407691662d14ee8d80ea02496fd83ee3f639c23e..f6f7ccffdb005d097cd688b7388465cc025214c5 100644 (file)
 ///
 /// ```
 /// use std::mem::{self, MaybeUninit};
-/// use std::ptr;
 ///
 /// let data = {
 ///     // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
 ///         MaybeUninit::uninit().assume_init()
 ///     };
 ///
-///     // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
-///     // we have a memory leak, but there is no memory safety issue.
+///     // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
+///     // assignment instead of `ptr::write` does not cause the old
+///     // uninitialized value to be dropped. Also if there is a panic during
+///     // this loop, we have a memory leak, but there is no memory safety
+///     // issue.
 ///     for elem in &mut data[..] {
-///         unsafe { ptr::write(elem.as_mut_ptr(), vec![42]); }
+///         *elem = MaybeUninit::new(vec![42]);
 ///     }
 ///
 ///     // Everything is initialized. Transmute the array to the
 /// let mut data_len: usize = 0;
 ///
 /// for elem in &mut data[0..500] {
-///     unsafe { ptr::write(elem.as_mut_ptr(), String::from("hello")); }
+///     *elem = MaybeUninit::new(String::from("hello"));
 ///     data_len += 1;
 /// }
 ///