本文簡要介紹rust語言中 std::mem::MaybeUninit.assume_init_read
的用法。
用法
pub unsafe fn assume_init_read(&self) -> T
從 MaybeUninit<T>
容器中讀取值。生成的T
將接受通常的丟棄處理。
隻要有可能,最好使用 assume_init
代替,這樣可以防止重複 MaybeUninit<T>
的內容。
安全性
由調用者來保證 MaybeUninit<T>
確實處於初始化狀態。當內容尚未完全初始化時調用此方法會導致未定義的行為。 type-level 文檔包含有關此初始化不變量的更多信息。
此外,與 ptr::read
函數類似,此函數創建內容的按位副本,無論包含的類型是否實現 Copy
特征。當使用數據的多個副本時(通過多次調用 assume_init_read
,或先調用 assume_init_read
然後 assume_init
),您有責任確保數據確實可能重複。
例子
此方法的正確用法:
#![feature(maybe_uninit_extra)]
use std::mem::MaybeUninit;
let mut x = MaybeUninit::<u32>::uninit();
x.write(13);
let x1 = unsafe { x.assume_init_read() };
// `u32` is `Copy`, so we may read multiple times.
let x2 = unsafe { x.assume_init_read() };
assert_eq!(x1, x2);
let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
x.write(None);
let x1 = unsafe { x.assume_init_read() };
// Duplicating a `None` value is okay, so we may read multiple times.
let x2 = unsafe { x.assume_init_read() };
assert_eq!(x1, x2);
此方法的錯誤使用:
#![feature(maybe_uninit_extra)]
use std::mem::MaybeUninit;
let mut x = MaybeUninit::<Option<Vec<u32>>>::uninit();
x.write(Some(vec![0, 1, 2]));
let x1 = unsafe { x.assume_init_read() };
let x2 = unsafe { x.assume_init_read() };
// We now created two copies of the same vector, leading to a double-free ⚠️ when
// they both get dropped!
相關用法
- Rust MaybeUninit.assume_init_ref用法及代碼示例
- 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_read。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。