According to example in UnsafeCell in std::cell - Rust, it says " Gradual initialization of an UnsafeCell
requires raw_get
, as calling get
would require creating a reference to uninitialized data:"
// example from rust-std docs
let m = MaybeUninit::<UnsafeCell<i32>>::uninit();
unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); }
let uc = unsafe { m.assume_init() };
assert_eq!(uc.into_inner(), 5);
If I implement same function as below, is it undefined behavior?
get_mut
just return reference to &mut MaybeUninit
, and call the write
method, which should be safe according to MaybeUinit docs, but then why the above docs says " Gradual initialization of an UnsafeCell
requires raw_get
let mut m = UnsafeCell::new(MaybeUninit::<i32>::uninit());
// Is it UB?
m.get_mut().write(5);
assert_eq!(unsafe {m.into_inner().assume_init()}, 5);