Move Semantics & Rvalue References
Prerequisites: Smart pointers
Copying a large object (a vector with a million elements, say)
is expensive — move semantics (C++11) let ownership of that
object's internal data transfer instead, leaving the source in a
valid-but-unspecified "moved-from" state, for the cost of just
copying a few pointers.
std::vector<int> makeData() {
std::vector<int> result = {1, 2, 3, 4, 5};
return result; // moved out, not copied, on return
}
std::vector<int> a = makeData(); // move, not copy
std::vector<int> b = std::move(a); // explicit move — a is now empty
std::move doesn't itself move anything — it's a cast that marks a
value as safe to move from, which the receiving constructor or
assignment operator then actually acts on.
Common mistakes
- Using a variable after
std::moveing it, expecting its old contents to still be there — a moved-from object is only guaranteed to be in some valid state, not its original one.