struct Node(i32, Option<Box<Node>>);
fn main() {
let nod = Node(0, None);
let ptr = unsafe {
&nod as *const Node
};
let x = nod; // value moved
let y = unsafe {
(*ptr).0 // invalid dereference?
};
}
In the above code, ptr holds the address of a stack object nod. However, since ptr bypasses the borrow checker, we can assess a nod after its value moves.
The memory of nod is allocated in stack and keeps alive until main finishes. And the move of nod only does a bitwise copy. My question is, how Rust think about this issue? If we obey the ownership rule, the dereference of ptr is invalid. Otherwise, it is safe.
If you move a variable somewhere else and it's in a register, the compiler might reuse the register for something else. But since one is taking the address the variable must be spilled to the stack.
Isn't the compiler allowed to reuse stack space to another variable after the current variable there were unconditionally moved out? Before the end of scope
Not necessarily. It could be optimized into something that doesn’t use the address.
It is currently unclear whether the compiler should be allowed to do that or not (in the case where the compiler can’t prove that nothing is holding a pointer to that variable). See the discussion I linked. One of the difficulties is: How to handle partial moves?