当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust read用法及代码示例


本文简要介绍rust语言中 Function core::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-lang.org大神的英文原创作品 Function core::ptr::read。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。