It’s not even a problem for the pointer to still exist or be moved/copied around while a mutable reference (derived from the pointer) to its target exists. You just can’t dereference the pointer. For a function fn can_alias(obj1: &mut Obj, obj2: *mut Obj) {}
where obj1
is expected to be derived from obj2
that means the function must not dereference obj2
at all during it’s call. (A function argument is always considered alive throughout the function, it doesn’t matter if or where you use obj1
inside of can_alias
. Edit: Actually, nevermind, this might not be true. I'm not sure what restrictions apply. I don't know whether or not it's e. g. allowed to stop using obj1
and then start using obj2
in such a function.)
Another thing to keep in mind when working with references and pointers: If you derive a reference from a pointer, then a new pointer from that reference, the new pointer must only be used while the reference is still alive. I.e. if you have a ptr: *mut T
then
let ptr_copy: *mut T = ptr;
is fundamentally different from
let ptr_copy: *mut T = &mut *ptr;
The former allows you to use ptr_copy
and ptr
interchangably. So you may e.g. alternate writing to ptr_copy
and ptr
afterwards. OTOH in the latter case, ptr_copy
becomes immediately invalidated once you use ptr
again.
If you “derive” a pointer from a reference by copying one of it’s target’s fields, which happens to be a pointer, this is of course not a problem.
Something like
struct Foo(*mut Bar);`
let ptr: *mut Foo = …;
let reference = &mut *ptr;
let derived: *mut Bar = reference.0; // copies the field
// continue using BOTH `ptr` and `derived` …
is totally fine. Even if you then do it another time
let another_reference = &mut *ptr;
let another_derived: *mut Bar = another_reference.0; // copies the field
// continue using `ptr`, `derived`, and `another_derived` …
it’s not a problem.
Edit: Fixed a typo, I had “let another_derived: *mut Bar = reference.0;
” before which would’ve been undefined behavior of course, because another_reference
was already created.