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


Rust write用法及代码示例


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