本文简要介绍rust语言中 std::mem::MaybeUninit.assume_init_ref
的用法。
用法
pub unsafe fn assume_init_ref(&self) -> &T
获取对包含值的共享引用。
当我们想要访问已初始化但没有 MaybeUninit
所有权的 MaybeUninit
(防止使用 .assume_init()
)时,这可能很有用。
安全性
当内容尚未完全初始化时调用此方法会导致未定义的行为:由调用者来保证 MaybeUninit<T>
确实处于初始化状态。
例子
此方法的正确用法:
use std::mem::MaybeUninit;
let mut x = MaybeUninit::<Vec<u32>>::uninit();
// Initialize `x`:
x.write(vec![1, 2, 3]);
// Now that our `MaybeUninit<_>` is known to be initialized, it is okay to
// create a shared reference to it:
let x: &Vec<u32> = unsafe {
// SAFETY: `x` has been initialized.
x.assume_init_ref()
};
assert_eq!(x, &vec![1, 2, 3]);
不正确此方法的用法:
use std::mem::MaybeUninit;
let x = MaybeUninit::<Vec<u32>>::uninit();
let x_vec: &Vec<u32> = unsafe { x.assume_init_ref() };
// We have created a reference to an uninitialized vector! This is undefined behavior. ⚠️
use std::{cell::Cell, mem::MaybeUninit};
let b = MaybeUninit::<Cell<bool>>::uninit();
// Initialize the `MaybeUninit` using `Cell::set`:
unsafe {
b.assume_init_ref().set(true);
// ^^^^^^^^^^^^^^^
// Reference to an uninitialized `Cell<bool>`: UB!
}
相关用法
- Rust MaybeUninit.assume_init_read用法及代码示例
- Rust MaybeUninit.assume_init_mut用法及代码示例
- Rust MaybeUninit.assume_init用法及代码示例
- Rust MaybeUninit.as_ptr用法及代码示例
- Rust MaybeUninit.as_mut_ptr用法及代码示例
- Rust MaybeUninit.array_assume_init用法及代码示例
- Rust MaybeUninit.write_slice用法及代码示例
- Rust MaybeUninit.zeroed用法及代码示例
- Rust MaybeUninit.write_slice_cloned用法及代码示例
- Rust MaybeUninit.write用法及代码示例
- Rust MaybeUninit.uninit用法及代码示例
- Rust MaybeUninit.new用法及代码示例
- Rust MaybeUninit.uninit_array用法及代码示例
- Rust MaybeUninit用法及代码示例
- Rust ManuallyDrop用法及代码示例
- Rust ManuallyDrop.into_inner用法及代码示例
- Rust ManuallyDrop.new用法及代码示例
- Rust Map用法及代码示例
- Rust Mutex.new用法及代码示例
- Rust MetadataExt.st_ctime_nsec用法及代码示例
- Rust MetadataExt.mtime_nsec用法及代码示例
- Rust MetadataExt.nlink用法及代码示例
- Rust MulAssign.mul_assign用法及代码示例
- Rust Mutex.get_mut用法及代码示例
- Rust MetadataExt.st_atime用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::mem::MaybeUninit.assume_init_ref。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。