Move semantics
Move semantics is the language feature that transfers resources from an expiring object instead of copying them. It is built from rvalue references, move constructors, move assignment, and std::move. The source stays alive in a valid empty-ish state.
Detailed Explanation
Before C++11, returning a std::vector from a function copied the buffer, or relied on named return value optimisation as a quality-of-implementation hope. Large objects were passed by const reference and then copied into a member. Auto_ptr tried to fake transfer with a copy constructor that mutated its source, and broke standard containers.
Move semantics made transfer a first-class operation. An rvalue — a temporary, or a named object you have finished with — may bind to T&&. Overload resolution then picks the move constructor or move assignment. Those functions steal pointers instead of allocating. An lvalue still binds to const T& and copies, so a name you still need is not emptied by accident.
The pieces:
- Value categories. Lvalues are durable names. Rvalues are temporaries and expiring objects.
std::move(x)is a cast from lvalue to rvalue, not a move by itself. - Move constructor
T(T&&). Builds a new object from an rvalue. - Move assignment
T& operator=(T&&). Replaces an existing object from an rvalue. - Moved-from state. The source is a live object. Destroy it or assign to it. Do not assume it still holds its old value.
noexceptmoves. Containers askis_nothrow_move_constructibleand move on grow only when the answer is yes.
What actually moves is whatever the type says. int is copied; there is nothing to steal. std::string steals the heap buffer (and may also steal the small-string inline buffer by copying the bytes). std::array moves each element; it has no heap pointer of its own. std::unique_ptr transfers ownership and leaves the source empty. A class of those members moves memberwise if you let the compiler write the operations.
Move semantics is also an API convention. A function that takes T by value is saying "I will own a T". Callers write f(std::move(x)) to transfer or f(x) to copy. A function that takes T&& is saying "I only accept temporaries or explicit moves" — a sink. A function that takes const T& is saying "I will read, I will not steal".
The performance story is: moves turn an O(n) copy of a buffer into an O(1) pointer swap, except when the type has no buffer. They do not make your program faster if you still copy because you forgot std::move on a named source you are done with, or if you std::move a type whose move is a copy.
Correctness story: types that are move-only (unique_ptr, thread, fstream in practice) cannot be put in a std::array that you copy, and cannot be used with algorithms that require CopyConstructible. They can live in a vector because vector moves on reallocation when allowed.
Code Examples
#include <iostream>
#include <string>
#include <utility>
#include <vector>
void take(std::vector<std::string> lines) {
std::cout << lines.size() << '\n';
}
int main() {
std::vector<std::string> lines{"a", "b", "c"};
take(lines); // copy: lines still has 3 elements
std::cout << lines.size() << '\n'; // prints: 3 then 3
take(std::move(lines)); // transfer
std::cout << lines.size() << '\n'; // prints: 3 then 0
}#include <memory>
#include <utility>
struct Conn {
std::unique_ptr<int> socket;
};
int main() {
Conn a{std::make_unique<int>(7)};
Conn b = std::move(a); // Conn is movable, not copyable
// Conn c = a; // error after a was moved; also error before
(void)b;
}Common Gotchas
Using a moved-from object as if nothing happened
`lines[0]` after `std::move(lines)` into another vector is out of range. Reset or assign first.
Returning a local already moves
`return std::move(local)` can prevent elision. Write `return local;`.
Memberwise move of a class that caches `this`
a pointer-to-self inside the object still points at the source after a defaulted move. Write a custom move that rebinds it.