about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorMark Rousskov <mark.simulacrum@gmail.com>2019-07-15 19:55:04 -0400
committerGitHub <noreply@github.com>2019-07-15 19:55:04 -0400
commitcaf10b5ffe6977e79f8d5f1bb407d99d2b015b4a (patch)
treefb978b5d347bf9e155faab504c586249b403c8a5 /src/libcore
parent64ceba73afca4eddf1409427413fed5ed6711270 (diff)
parentcb3aa4ce2c5de3ffb38afb2ca6d7cf19cb3e9be7 (diff)
downloadrust-caf10b5ffe6977e79f8d5f1bb407d99d2b015b4a.tar.gz
rust-caf10b5ffe6977e79f8d5f1bb407d99d2b015b4a.zip
Rollup merge of #62634 - llogiq:uninit-array-docs, r=RalfJung
Less unsafe in the array example of MaybeUninit docs

I believe this is an acceptable way to initialize elements of `[MaybeUninit<T>; _]` arrays. Miri agrees. Conceptually, we are working at the array level, above the `MaybeUninit`, and as we are replacing it wholesale, this should pose no problem to soundness. And the code is easier to read.

r? @RalfJung
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/mem/maybe_uninit.rs12
1 files changed, 7 insertions, 5 deletions
diff --git a/src/libcore/mem/maybe_uninit.rs b/src/libcore/mem/maybe_uninit.rs
index 407691662d1..f6f7ccffdb0 100644
--- a/src/libcore/mem/maybe_uninit.rs
+++ b/src/libcore/mem/maybe_uninit.rs
@@ -112,7 +112,6 @@ use crate::mem::ManuallyDrop;
 ///
 /// ```
 /// use std::mem::{self, MaybeUninit};
-/// use std::ptr;
 ///
 /// let data = {
 ///     // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
@@ -122,10 +121,13 @@ use crate::mem::ManuallyDrop;
 ///         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
@@ -151,7 +153,7 @@ use crate::mem::ManuallyDrop;
 /// 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;
 /// }
 ///