Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Less unsafe in the array example of MaybeUninit docs #62634

Merged
merged 1 commit into from
Jul 16, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/libcore/mem/maybe_uninit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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;
/// }
///
Expand Down