How does Rust move stack variables that are not Copyable?

别说谁变了你拦得住时间么 提交于 2019-12-04 00:24:18

Does it physically get moved to do_something()'s stack frame?

Yes. Non-Copy types are physically moved exactly like Copy types are: with a memcpy. You already understood that primitive Copy-types are copied into the new location (new stack frame for example) byte-by-byte.

Now consider this implementation of Box:

struct Box<T> {
    ptr: *const T,
}

When you have

let b = Box::new(27i32);
do_something(b);    // `b` is moved into `do_something`

then an i32 is allocated on the heap and the Box saves the raw pointer to that heap allocated memory. Note that the Box directly (the raw pointer inside) is directly on the stack, not on the heap! Just the i32 is on the heap.

When the Box is moved, it is memcpyed, as I just said. This means that the stack contents are copied (!!)... thus just the pointer is copied byte-by-byte. There isn't a second version of the i32!

There is no difference between Copy and non-Copy types when it comes to moving physically. The only difference is that the compiler enforces different rules upon those types.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!