本文簡要介紹rust語言中 Function std::ptr::read
的用法。
用法
pub unsafe fn read<T>(src: *const T) -> T
從src
讀取值而不移動它。這使src
中的內存保持不變。
安全性
如果違反以下任何條件,則行為未定義:
-
src
必須是 valid 才能讀取。 -
src
必須正確對齊。如果不是這種情況,請使用read_unaligned
。 -
src
必須指向T
類型的正確初始化值。
請注意,即使 T
的大小為 0
,指針也必須非空且正確對齊。
例子
基本用法:
let x = 12;
let y = &x as *const i32;
unsafe {
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");
返回值的所有權
read
創建 T
的按位副本,無論 T
是否為 Copy
。如果 T
不是 Copy
,則同時使用返回值和 *src
處的值可能會違反內存安全。請注意,分配給 *src
算作使用,因為它將嘗試刪除 *src
處的值。
write()
可用於覆蓋數據而不會導致數據被丟棄。
use std::ptr;
let mut s = String::from("foo");
unsafe {
// `s2` now points to the same underlying memory as `s`.
let mut s2: String = ptr::read(&s);
assert_eq!(s2, "foo");
// Assigning to `s2` causes its original value to be dropped. Beyond
// this point, `s` must no longer be used, as the underlying memory has
// been freed.
s2 = String::default();
assert_eq!(s2, "");
// Assigning to `s` would cause the old value to be dropped again,
// resulting in undefined behavior.
// s = String::from("bar"); // ERROR
// `ptr::write` can be used to overwrite a value without dropping it.
ptr::write(&mut s, String::from("bar"));
}
assert_eq!(s, "bar");
相關用法
- Rust read用法及代碼示例
- Rust read_to_string用法及代碼示例
- Rust read_link用法及代碼示例
- Rust ready用法及代碼示例
- Rust read_unaligned用法及代碼示例
- Rust read_dir用法及代碼示例
- Rust read_volatile用法及代碼示例
- Rust rename用法及代碼示例
- Rust remove_dir_all用法及代碼示例
- Rust remove_file用法及代碼示例
- Rust resume_unwind用法及代碼示例
- Rust repeat用法及代碼示例
- Rust remove_dir用法及代碼示例
- Rust remove_var用法及代碼示例
- Rust repeat_with用法及代碼示例
- Rust replace用法及代碼示例
- Rust range用法及代碼示例
- 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-lang.org大神的英文原創作品 Function std::ptr::read。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。