“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

Move semantics: stealing, not copying

Learn

Lesson 2 of 7 standard ~6 min

Copying a vector duplicates its entire buffer. But if the source is an rvalue — a temporary about to be destroyed — duplicating is waste: nobody will look at the original again. Move semantics lets the new object steal the source's internals (its pointer, size, capacity) and leave the husk behind for a cheap destruction. The trick is telling the compiler "this one is safe to gut."

First, the single most misunderstood function in the language. What does std::move actually do?

standardMultiple choice

What does std::move(x) actually do at runtime?

Go deeper ↓Ownership by diff

Because it is only a cast, the real work happens in the move constructor it selects. Predict what that work leaves behind.

standardPredict + reveal

What does this print? Pay attention to the state of a after the move.

std::vector<int> a = {1, 2, 3};
std::vector<int> b = std::move(a);
std::cout << b.size() << " " << a.size();

Lock in the vocabulary — name the function that does the stealing.

standardShort answer

Name the special member function that constructs a new object by stealing the resources of an expiring one. Two words.

Go deeper ↓Ownership by diff