这是我的代码:
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
特征,所以它失败了。有人可以向我解释一下吗?提前致谢。
最佳答案
无需过多了解您尝试做的事情,就很容易解决此问题。该错误来自unsafe {}
将操作分为两部分的事实。每当您要将原始指针变成引用时,都不要分割&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
关于rust - 返回原始指针指向的数据引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66540586/