use core::marker::PhantomData;
fn main() {
struct Inspector<'a>(&'a u8);
impl<'a> Drop for Inspector<'a> {
fn drop(&mut self) {
println!("I was only {} days from retirement!", self.0);
}
}
struct Uniqu<T> {
ptr: *mut T,
marker: PhantomData<T>,
}
struct World<'a> {
ptr: Option<Uniqu<Inspector<'a>>>,
days: u8,
}
let mut world = World{ptr: None, days:1};
let mut inspector = Inspector(&world.days);
let mut uniqu = Uniqu::<Inspector>{ptr: &mut inspector, marker: PhantomData};
world.ptr = Some(uniqu);
}
通过引用drop check规则,它不能成功编译。但成功。如果我使用这样的代码:
use core::marker::PhantomData;
fn main() {
struct Inspector<'a>(&'a u8);
impl<'a> Drop for Inspector<'a> {
fn drop(&mut self) {
println!("I was only {} days from retirement!", self.0);
}
}
struct World<'a> {
ptr: Option<Box<Inspector<'a>>>,
days: u8,
}
let mut world = World{ptr: None, days:1};
let mut inspector = Inspector(&world.days);
world.ptr = Some(Box::new(inspector));
}
只需使用Box而不是Uniqu In World struct,它编译失败:
error[E0597]: `world.days` does not live long enough
--> src/main.rs:21:35
|
21 | let mut inspector = Inspector(&world.days);
| ^^^^^^^^^^^ borrowed value does not live long enough
...
26 | }
| -
| |
| `world.days` dropped here while still borrowed
| borrow might be used here, when `world` is dropped and runs the destructor for type `World<'_>`
在这种情况下,drop checker已经检查过了。这就是我所需要的。
在第一种情况下,Drop Checker还没有检查它。PhantomData似乎不工作,为什么?
1条答案
按热度按时间fkaflof61#
在第一个示例中,
Uniqu
没有实现Drop
,因此它没有要检查的潜在不安全的删除代码。但是,
Box
确实实现了Drop
,因此它可以释放已分配的内存,这就是它没有通过丢弃检查器的原因。在您的第一个代码段中向
Uniqu
添加一个简单的Drop
实现确实会导致编译器拒绝代码as seen in the playground。