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

Document how MaybeUninit<Struct> can be initialized. #81580

Merged
merged 4 commits into from
Feb 6, 2021
Merged
Changes from 2 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
39 changes: 35 additions & 4 deletions library/core/src/mem/maybe_uninit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,41 @@ use crate::ptr;
///
/// ## Initializing a struct field-by-field
///
/// There is currently no supported way to create a raw pointer or reference
/// to a field of a struct inside `MaybeUninit<Struct>`. That means it is not possible
/// to create a struct by calling `MaybeUninit::uninit::<Struct>()` and then writing
/// to its fields.
/// You can use `MaybeUninit<T>`, and the [`std::ptr::addr_of_mut`] macro, to initialize structs field by field:
///
/// ```rust
/// use std::mem::MaybeUninit;
/// use std::ptr::addr_of_mut;
///
/// #[derive(Debug, PartialEq)]
/// pub struct Foo {
/// name: String,
/// list: Vec<u8>,
/// }
///
/// let foo = {
/// let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit();
/// let ptr = uninit.as_mut_ptr();
///
/// // Initializing the `name` field
/// unsafe { addr_of_mut!((*ptr).name).write("Bob".to_string()); }
///
/// // Initializing the `list` field
/// // If there was a panic here, then the `String` in the `name` field would be leaked.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Language nitpick: would be leaked --> leaks

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the leak can be avoided by reordering the code a bit?

let name = ...
let list = ...

unsafe {
   addr_of_mut!((*ptr).name).write(name);
   addr_of_mut!((*ptr).list).write(list);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@the8472 In this case yes, but I wanted this to translate to how one would initialize a large struct field by field.
If the struct had been a heap allocated struct with a large array field instead of a Vec, it wouldn't be possible to construct the array on the stack before moving it to the field in debug builds, since it would overflow the stack.

Copy link
Member

@the8472 the8472 Jan 31, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, afaik currently there is no guarantee that passing a large array directly to function arguments gets optimized any better than first assigning it to a named variable. You're at the mercy of the optimizer in either case since there's no placement API. rust-lang/rfcs#2884 is still under discussion.

I think to initialize a large array without blowing the stack in debug mode you would have to loop over each item.

/// unsafe { addr_of_mut!((*ptr).list).write(vec![0, 1, 2]); }
///
/// // All the fields are initialized, so we call `assume_init` to get an initialized Foo.
/// unsafe { uninit.assume_init() }
/// };
///
/// assert_eq!(
/// foo,
/// Foo {
/// name: "Bob".to_string(),
/// list: vec![0, 1, 2]
/// }
/// );
/// ```
///
/// [ub]: ../../reference/behavior-considered-undefined.html
///
Expand Down