當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。