I'm implementing an algorithm, and in order to maintain the desired time complexity, I would like to hold a pointer to an element of a Vec
while the Vec
is being moved.
Specifically, something like this:
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3];
let ptr: *mut usize = &mut v[1] as *mut usize;
let mut u: Vec<usize> = v;
assert!(ptr == &mut u[1] as *mut usize);
println!("{}", unsafe { *ptr });
}
The actual code is more complicated, and involves a tree-like data structure where each vertex owns a Vec
of children. I'm not asking about coding style here, but my question is about whether this code can be relied on to do what I think it does.
Since Vec
has to hold its content on the heap, and moves are equivalent to memcpy
in Rust, I think the fact that Vec
is movable would imply that my code is sound (i.e. not undefined behaviour). Is this correct?