【问题标题】:Returning a reference of data that a raw pointer point to返回原始指针指向的数据的引用
【发布时间】:2021-03-09 03:54:52
【问题描述】:

这是我的代码:

use std::ptr::NonNull;
struct S {
    i: i32
}

impl Clone for S {
    fn clone(&self) -> Self {
        S {
            i: self.i
        }
    }
}

struct F {
    v: Vec<NonNull<S>>
}

impl F {
    pub fn func<'a>(&'a self) -> &'a mut S {
        let s = &mut unsafe {
            *self.v[0].as_ptr()
        };
        s
    }
}


fn main() {
    let f = F {
        v: vec![NonNull::new_unchecked(Box::into_raw(Box::new(S{i: 32}.clone()))); 5]
    };
    f.func();
}

当我编译它时,编译器提醒我“返回一个引用当前函数拥有的数据的值”

这是我的问题:当我取消引用原始指针时,它指向的数据不应该归结构 self 所有?它怎么会被当前功能所拥有。当我取消引用原始指针时,编译器也会提醒我 “移动发生”。但是我没有为结构 S 实现 Copy 特征,所以它失败了。

有人可以向我解释一下吗?提前致谢。

【问题讨论】:

  • 仅供参考,您的 func 非常危险,因为两次调用它会创建两个指向相同数据的可变引用,这违反了 Rust 的安全规则。

标签: rust


【解决方案1】:

无需过多了解您正在尝试做的事情的背景,解决这个问题真的很容易。错误来自unsafe {} 将操作分成两部分这一事实。每当您想将原始指针转换为引用时,请不要拆分 &amp;mut *x

// Take a new mutable reference to whatever is returned by the unsafe {} block
let s = &mut unsafe {
    // Copy whatever is stored at the raw pointer to a new owned value
    *self.v[0].as_ptr()
};

let s = unsafe {
    // Create a new mutable reference to a raw pointer
    &mut *self.v[0].as_ptr()
};

之后,您只需将NonNull::new_unchecked 标记为不安全即可。

rust playground link

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多