Hacker News new | ask | show | jobs
by cormacrelf 2308 days ago
You’ve referred to two kinds of move there — memmove (overlapping) vs memcpy (non-overlapping memory) and transfers of ownership. In C++ a move appears to always require moving memory with either (depending on aliasing) or via registers. Is that correct?

In Rust, the only thing that has to happen is a transfer of ownership, which does not always mean moving bytes. This greatly simplifies the whole “rvalue reference parameter” thing, because ownership abstracts over wherever you might want to move to. So if your new owner wants it in part of its new stack frame, the compiler is free to just put it there before calling or simply call a destructor on the parent stack frame’s memory in the child. (I don’t know exactly what it likes to do, but it’s all fine.) New owners like Box need to move memory, and that’s cool too, and the compiler is free to reorder the steps to avoid initialising and moving when “placement new” is better. This is also something I believe the compiler is getting better at slowly. The compiler won’t let you safely write moves out of a vector without mutating or taking ownership of the vector, each with moving bytes — otherwise it has access to something it no longer owns.

The easiest example is `let a = A::new(); let b = a;`, which only needs stack space for one A, and for which line 2 is a noop. Its only effect is in when drop is called, if b is in a smaller scope. Does C++ do this too? I would hope so, but it looks like no.

Edit: turns out neither do it.

- https://rust.godbolt.org/z/xjA9v4 - https://godbolt.org/z/7Wh_AZ