我试图在创建结构和删除结构时记录结构地址,当我运行以下代码时,不仅两个结构都记录相同的地址,而且两个结构在删除时都记录不同的地址。有没有正确的方法来做到这一点?
struct TestStruct {
val: i32
}
impl TestStruct {
fn new(val: i32) -> Self {
let x = TestStruct{val};
println!("creating struct {:p}", &x as *const _);
x
}
}
impl Drop for TestStruct {
fn drop(&mut self) {
println!("destroying struct {:p}", &self as *const _)
}
}
fn main() {
let s1 = TestStruct::new(1);
let s2 = TestStruct::new(2);
}
Run Code Online (Sandbox Code Playgroud)
输出:
creating struct 0x7ffef1f96e44
creating struct 0x7ffef1f96e44
destroying struct 0x7ffef1f96e38
destroying struct 0x7ffef1f96e38
Run Code Online (Sandbox Code Playgroud)
在new()您打印 的地址时x,当new()返回x移动时,它不再是实际地址,这就是为什么您会看到重复的相同地址。
另请参阅“返回值是否移动?” .
在 中drop(),您实际上是在打印 的地址&Self而不是Self其本身。你需要改变&self as *const _,只是self为self已经是一个参考。现在它正确打印了两个不同的地址。
如果再改为尝试打印的地址s1,并s2在main()随后的地址匹配。
impl TestStruct {
fn new(val: i32) -> Self {
let x = TestStruct { val };
x
}
}
impl Drop for TestStruct {
fn drop(&mut self) {
println!("destroying struct {:p}", self);
}
}
fn main() {
let s1 = TestStruct::new(1);
println!("creating struct {:p}", &s1);
let s2 = TestStruct::new(2);
println!("creating struct {:p}", &s2);
}
Run Code Online (Sandbox Code Playgroud)
输出:
creating struct 0xb8682ff59c <- s1
creating struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff59c <- s1
Run Code Online (Sandbox Code Playgroud)