Merge pull request #492 from senekor/senekor-oupvrwkspumq

Use inline const expression in unchecked-uninit.md
master
Yuki Okushi 1 month ago committed by GitHub
commit 8b61acfaea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -23,12 +23,8 @@ use std::mem::{self, MaybeUninit};
const SIZE: usize = 10; const SIZE: usize = 10;
let x = { let x = {
// Create an uninitialized array of `MaybeUninit`. The `assume_init` is // Create an uninitialized array of `MaybeUninit`.
// safe because the type we are claiming to have initialized here is a let mut x = [const { MaybeUninit::uninit() }; SIZE];
// bunch of `MaybeUninit`s, which do not require initialization.
let mut x: [MaybeUninit<Box<u32>>; SIZE] = unsafe {
MaybeUninit::uninit().assume_init()
};
// Dropping a `MaybeUninit` does nothing. Thus using raw pointer // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
// assignment instead of `ptr::write` does not cause the old // assignment instead of `ptr::write` does not cause the old
@ -48,14 +44,7 @@ println!("{x:?}");
This code proceeds in three steps: This code proceeds in three steps:
1. Create an array of `MaybeUninit<T>`. With current stable Rust, we have to use 1. Create an array of `MaybeUninit<T>`.
unsafe code for this: we take some uninitialized piece of memory
(`MaybeUninit::uninit()`) and claim we have fully initialized it
([`assume_init()`][assume_init]). This seems ridiculous, because we didn't!
The reason this is correct is that the array consists itself entirely of
`MaybeUninit`, which do not actually require initialization. For most other
types, doing `MaybeUninit::uninit().assume_init()` produces an invalid
instance of said type, so you got yourself some Undefined Behavior.
2. Initialize the array. The subtle aspect of this is that usually, when we use 2. Initialize the array. The subtle aspect of this is that usually, when we use
`=` to assign to a value that the Rust type checker considers to already be `=` to assign to a value that the Rust type checker considers to already be
@ -165,7 +154,6 @@ anywhere expects to be handed uninitialized memory, so if you're going to pass
it around at all, be sure to be *really* careful. 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
[`ptr`]: ../core/ptr/index.html [`ptr`]: ../core/ptr/index.html
[raw_reference]: ../reference/types/pointer.html#r-type.pointer.raw.constructor [raw_reference]: ../reference/types/pointer.html#r-type.pointer.raw.constructor
[`write`]: ../core/ptr/fn.write.html [`write`]: ../core/ptr/fn.write.html

Loading…
Cancel
Save