本文簡要介紹rust語言中 Function core::ptr::write
的用法。
用法
pub unsafe fn write<T>(dst: *mut T, src: T)
用給定值覆蓋內存位置,而不讀取或刪除舊值。
write
不會刪除 dst
的內容。這是安全的,但它可能會泄漏分配或資源,因此應注意不要覆蓋應刪除的對象。
此外,它不會刪除 src
。從語義上講,src
被移動到 dst
指向的位置。
這適用於初始化未初始化的內存,或覆蓋以前來自 read
的內存。
安全性
如果違反以下任何條件,則行為未定義:
-
對於寫入,
dst
必須是 valid。 -
dst
必須正確對齊。如果不是這種情況,請使用write_unaligned
。
請注意,即使 T
的大小為 0
,指針也必須非空且正確對齊。
例子
基本用法:
let mut x = 0;
let y = &mut x as *mut i32;
let z = 12;
unsafe {
std::ptr::write(y, z);
assert_eq!(std::ptr::read(y), 12);
}
手動實現 mem::swap
:
use std::ptr;
fn swap<T>(a: &mut T, b: &mut T) {
unsafe {
// Create a bitwise copy of the value at `a` in `tmp`.
let tmp = ptr::read(a);
// Exiting at this point (either by explicitly returning or by
// calling a function which panics) would cause the value in `tmp` to
// be dropped while the same value is still referenced by `a`. This
// could trigger undefined behavior if `T` is not `Copy`.
// Create a bitwise copy of the value at `b` in `a`.
// This is safe because mutable references cannot alias.
ptr::copy_nonoverlapping(b, a, 1);
// As above, exiting here could trigger undefined behavior because
// the same value is referenced by `a` and `b`.
// Move `tmp` into `b`.
ptr::write(b, tmp);
// `tmp` has been moved (`write` takes ownership of its second argument),
// so nothing is dropped implicitly here.
}
}
let mut foo = "foo".to_owned();
let mut bar = "bar".to_owned();
swap(&mut foo, &mut bar);
assert_eq!(foo, "bar");
assert_eq!(bar, "foo");
相關用法
- Rust write_volatile用法及代碼示例
- Rust write用法及代碼示例
- Rust write_unaligned用法及代碼示例
- Rust writeln用法及代碼示例
- Rust write_bytes用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
- Rust RefCell.try_borrow_unguarded用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Function core::ptr::write。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。