如何PhantomData在Rust工作?在Nomicon中,它说如下:
为了告诉dropck我们自己拥有类型T的值,因此当我们删除时可能会丢弃一些T,我们必须添加一个额外的PhantomData来说明这一点.
对我而言,似乎暗示当我们PhantomData向结构中添加一个字段时,比如说是一个结构Vec.
pub struct Vec<T> {
data: *mut T,
length: usize,
capacity: usize,
phantom: PhantomData<T>,
}
Run Code Online (Sandbox Code Playgroud)
drop checker应该禁止以下代码序列:
fn main() -> () {
let mut vector = Vec::new();
let x = Box::new(1 as i32);
let y = Box::new(2 as i32);
let z = Box::new(3 as i32);
vector.push(x);
vector.push(y);
vector.push(z);
}
Run Code Online (Sandbox Code Playgroud)
由于的释放x,y以及z将发生前的的释放Vec,我会期望从编译器的一些投诉.但是,如果您运行上面的代码,则没有警告或错误.
为什么Rust编译器发出错误请求我约束以下结构中泛型参数的生命周期?
pub struct NewType<'a, T> {
x: &'a T,
}
Run Code Online (Sandbox Code Playgroud)
error[E0309]: the parameter type `T` may not live long enough
--> src/main.rs:2:5
|
2 | x: &'a T,
| ^^^^^^^^
|
= help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a T` does not outlive the data it points at
--> src/main.rs:2:5
|
2 | x: &'a T,
| ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
我可以通过更改来修复它
pub struct NewType<'a, T>
where
T: 'a,
{
x: &'a T,
} …Run Code Online (Sandbox Code Playgroud) 我正在测试Rust的一些不安全功能,主要是std::ptr函数,以查看我可能导致未定义行为的方式(仅仅是出于好奇).在下面的例子中我使用std::ptr::read()移动存储的地址x为y无uninitializing x.
读完之后,我以为我有两个指向堆上相同位置的指针.我的印象是,当我离开块时,x定义了x析构函数将被运行导致y指向释放的内存.但是,当我去打印它的值时*y,它仍然打印正确的值10.我阅读文档,但似乎无法弄清楚为什么这不是UB.如果有人能为我澄清这一点,我真的很感激.
PS.我来自C背景,所以对C的解释可能会让人更容易理解实际发生的事情.
fn main() {
let mut y: Box<i32>;
{
let x: Box<i32> = Box::new(10 as i32);
unsafe {
y = ptr::read(&x);
}
}
// I thought the destructor (free) would be called here on x
// making y point to invalid memory
// However, the following call to println! still works
println!("The value of y is {}", *y);
}
Run Code Online (Sandbox Code Playgroud)