In new()
you're printing the address of x
, when new()
returns x
is moved, so that is no longer the actual address, which is why you see the same address repeated.
See also "Is a returned value moved or not?".
In drop()
, you are actually printing the address of the &Self
and not Self
itself. You need to change &self as *const _
to just self
as self
is already a reference. Now it correctly prints the two different addresses.
If you then instead try to print the address of s1
and s2
in main()
then the addresses match.
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);
}
Output:
creating struct 0xb8682ff59c <- s1
creating struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff59c <- s1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…