Merge pull request #476 from nikthechampiongr/raw_ref

Update guidance on uninitialized fields to use &raw mut instead of addr_of_mut!
pull/478/head
Eric Huss 1 month ago committed by GitHub
commit d2c1d5cf8a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -134,7 +134,7 @@ to compute the address of array index `idx`. This relies on
how arrays are laid out in memory. how arrays are laid out in memory.
* For a struct, however, in general we do not know how it is laid out, and we * For a struct, however, in general we do not know how it is laid out, and we
also cannot use `&mut base_ptr.field` as that would be creating a also cannot use `&mut base_ptr.field` as that would be creating a
reference. So, you must carefully use the [`addr_of_mut`] macro. This creates reference. So, you must carefully use the [raw reference][raw_reference] syntax. This creates
a raw pointer to the field without creating an intermediate reference: a raw pointer to the field without creating an intermediate reference:
```rust ```rust
@ -147,7 +147,7 @@ struct Demo {
let mut uninit = MaybeUninit::<Demo>::uninit(); let mut uninit = MaybeUninit::<Demo>::uninit();
// `&uninit.as_mut().field` would create a reference to an uninitialized `bool`, // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
// and thus be Undefined Behavior! // and thus be Undefined Behavior!
let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) }; let f1_ptr = unsafe { &raw mut (*uninit.as_mut_ptr()).field };
unsafe { f1_ptr.write(true); } unsafe { f1_ptr.write(true); }
let init = unsafe { uninit.assume_init() }; let init = unsafe { uninit.assume_init() };
@ -167,7 +167,7 @@ it around at all, be sure to be *really* careful.
[`MaybeUninit`]: ../core/mem/union.MaybeUninit.html [`MaybeUninit`]: ../core/mem/union.MaybeUninit.html
[assume_init]: ../core/mem/union.MaybeUninit.html#method.assume_init [assume_init]: ../core/mem/union.MaybeUninit.html#method.assume_init
[`ptr`]: ../core/ptr/index.html [`ptr`]: ../core/ptr/index.html
[`addr_of_mut`]: ../core/ptr/macro.addr_of_mut.html [raw_reference]: ../reference/types/pointer.html#r-type.pointer.raw.constructor
[`write`]: ../core/ptr/fn.write.html [`write`]: ../core/ptr/fn.write.html
[`copy`]: ../std/ptr/fn.copy.html [`copy`]: ../std/ptr/fn.copy.html
[`copy_nonoverlapping`]: ../std/ptr/fn.copy_nonoverlapping.html [`copy_nonoverlapping`]: ../std/ptr/fn.copy_nonoverlapping.html

Loading…
Cancel
Save