I have this code:
struct Example {
x: i32,
b: Option<Box<Example>>,
}
impl Example {
fn get_self(&self) -> String {
format!("{:p}", self)
}
}
impl Drop for Example {
fn drop(&mut self) {
println!("Droppped: {} {:p}", self.x, self);
}
}
fn take(t: Example) {
println!("Taken ownership");
}
fn main() {
let mut myE = Example {
x: 1,
b: Some(Box::new(Example { x: 2, b: None })),
};
println!(
"Parent: {} Child: {}",
myE.get_self(),
match &myE.b {
Some(x) => x.get_self(),
None => String::from("Error"),
}
);
take(myE);
println!("End!");
}
And this is the output
Parent: 0x7ffdc8031560 Child: 0x556b88bb5ba0
Taken ownership
Droppped: 1 0x7ffdc80314a8
Droppped: 2 0x556b88bb5ba0
End!
Notice how the address of the child is the same address that is dropped once it goes out of scope but once the parent goes out of scope it changes for some reason. What is the reason for that?
I would expect the output to be something like this:
Parent: 0x7ffdc8031560 Child: 0x556b88bb5ba0
Taken ownership
Droppped: 1 0x7ffdc8031560
Droppped: 2 0x556b88bb5ba0
End!
Where the printed address is the same address that gets dropped.