0

Does a move result in a copy of the involved data on the stack, while all references to the heap are retained? The following example seems to indicate that this is the case:

use std::sync::{Arc};

struct A { v: Vec<u32> }

fn main() {
    let a = A { v: vec![42] };
    println!("{:p} {:p}", &a.v, &a.v[0]);
    let a_moved = a;
    println!("{:p} {:p}", &a_moved.v, &a_moved.v[0]);
    let arc_a_moved = Arc::new(a_moved);
    println!("{:p} {:p}", &arc_a_moved.clone().v, &arc_a_moved.clone().v[0]);
}
Lars Rönnbäck
  • 788
  • 1
  • 5
  • 11
  • Only if the type implement `Copy` trait. – Stargateur Jul 10 '17 at 08:27
  • Assuming that A is a very large struct, is there any way to prevent copying and just move the pointer? – Lars Rönnbäck Jul 10 '17 at 08:47
  • @LarsRönnbäck There's the idea of an `&move` reference, which allows just that, but it's not even in the rfc stage afaik. Until then you can use `&mut Option` and use `.take()` when you want to do your copy. `mem::drop(opt.take())` should get optimized out with aggressive optimizations. – oli_obk Jul 10 '17 at 10:41
  • Observe that you see very similar results with `struct A<'a> { v: &'a [u32] }`. It's not because `v[0]` is on the heap that its address is unchanged; it's because moves are shallow. – trent Jul 10 '17 at 13:39

0 Answers0