Move semantics and emplace_back
Stealing a temporary's resources instead of copying them — and the one keyword that decides whether std::vector will let you.
- Distinguish lvalues from rvalues, and copy constructors from move constructors
- Explain the difference between push_back and emplace_back
- Know why a move constructor should be noexcept
Copying a vector of a million elements copies a million elements. But if the source is a temporary that is about to be destroyed anyway, the copy is wasted: the new object could simply take over the old one’s heap block. That is a move.
C++ tells the two cases apart by the kind of expression. A named object is an lvalue — it lives on, so it must be copied. A temporary such as S() is an rvalue — nobody can refer to it afterwards, so it may be moved from. std::move(x) does not move anything by itself; it only casts x to an rvalue to say “I am done with this”.
Watching the constructors
22move_constructor.cpp gives a struct a constructor for each case and prints which one runs:
S() { std::cout << "Constructor!\n"; }
S(const S &s) { std::cout << "Copy constructor!\n"; }
S(S &&s) { std::cout << "Move Constructor!\n"; }
S s; // Constructor!
my_vector.push_back(S()); // Constructor! then Move Constructor!
push_back(S()) first builds a temporary, then move-constructs it into the vector’s storage. 23pushback_vs_emplaceback.cpp avoids even that:
my_vector.emplace_back(10); // only: Constructor!
emplace_back forwards its arguments to the constructor and builds the object directly in the vector’s slot — one constructor call, no temporary.
The noexcept trap
Push a few more elements and something surprising happens. When the vector reallocates (lesson 4), it must transfer the existing elements to the new block. If a move could throw halfway through, the old block would already be partly gutted and the vector could not roll back. So unless the move constructor is declared noexcept, std::vector plays safe and copies instead.
Measured with g++ 13, five emplace_back calls on an empty vector:
| Move constructor | Copies | Moves |
|---|---|---|
S(S &&s) (as in the repository) | 7 | 0 |
S(S &&s) noexcept | 0 | 7 |
The seven are the 1 + 2 + 4 elements carried across the reallocations at sizes 1, 2 and 4. For a type holding a large buffer, that is the difference between copying megabytes and swapping three pointers. The fix is one word:
S(S &&s) noexcept { ... }
The compiler-generated move constructor is noexcept automatically when all members’ moves are, which is one more reason to let the compiler write these functions whenever possible (the “rule of zero”).
Try it yourself. In 22move_constructor.cpp, push three S() objects in a loop and count the lines of output. Then add noexcept to the move constructor and count again. Finally call my_vector.reserve(3) first: how many “Copy” and “Move” lines remain, and why?