Copy the handle, not the data
Many objects are a small handle (a pointer and a size) to a large resource on the heap. Copying such an object means allocating and copying the resource. But if the source is about to die anyway, such as a temporary or a local being returned, you can steal its pointer and leave it empty. That is a move: a few word-sized assignments instead of an allocation and a memcpy.
The objective of this lesson: given any C++ expression, say whether it will copy or move, and write a class whose moves are cheap, correct and noexcept.
Value categories in one table
Every expression has a type and a value category. The category decides which overload (copy or move) is chosen.
| Category | Has identity (a name or address)? | Can be moved from? | Examples |
|---|---|---|---|
| lvalue | yes | no, unless you cast | x, v[i], *p, a named T&& parameter |
| xvalue | yes | yes | std::move(x), static_cast<T&&>(x) |
| prvalue | no | yes (and usually elided) | T{}, f() returning by value, a + b |
xvalues and prvalues together are rvalues. An rvalue reference T&& binds only to rvalues, so an overload taking T&& is selected exactly when the argument is safe to plunder.
Two facts trip up most candidates:
- A named rvalue reference is an lvalue. Inside
void f(Tracer&& r), the expressionrhas a name, soTracer kept = r;copies. You must writestd::move(r)again to move. std::movedoes not move anything. It isstatic_cast<T&&>: a cast to xvalue. The move happens only if overload resolution then picks a move constructor or move assignment.
Writing the move operations
A class that owns a raw resource needs the rule of five: destructor, copy constructor, copy assignment, move constructor, move assignment. (If its members are already RAII types such as std::vector or std::unique_ptr, write none of them: the rule of zero.)
#include <cstdio>
#include <cstring>
#include <utility>
#include <vector>
class Buffer {
public:
explicit Buffer(std::size_t n) : size_(n), data_(new char[n]) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer& other) : size_(other.size_), data_(new char[other.size_]) {
std::memcpy(data_, other.data_, size_);
std::puts("copy");
}
Buffer(Buffer&& other) noexcept
: size_(std::exchange(other.size_, 0)), data_(std::exchange(other.data_, nullptr)) {
std::puts("move");
}
Buffer& operator=(Buffer other) noexcept { // copy-and-swap: one operator for both
std::swap(size_, other.size_);
std::swap(data_, other.data_);
return *this;
}
std::size_t size() const { return size_; }
private:
std::size_t size_;
char* data_;
};
Buffer make(std::size_t n) { return Buffer(n); } // prvalue: guaranteed elision in C++17
int main() {
Buffer a(1024);
Buffer b = a; // lvalue source -> copy
Buffer c = std::move(a); // cast to rvalue -> move
std::printf("a.size()=%zu c.size()=%zu\n", a.size(), c.size());
Buffer d = make(64); // no copy, no move printed
std::printf("d.size()=%zu\n", d.size());
b = d; // parameter copy-constructed from lvalue -> copy
b = std::move(c); // parameter move-constructed -> move
std::printf("b.size()=%zu c.size()=%zu\n", b.size(), c.size());
}
Compiled with c++ -std=c++20 -O2 -Wall (Apple clang 17), it prints:
copy
move
a.size()=0 c.size()=1024
d.size()=64
copy
move
b.size()=1024 c.size()=0
Points to say out loud in an interview:
- The move constructor leaves the source in a valid but unspecified state; here it is precisely empty, so its destructor's
delete[] nullptris a no-op. For standard library types you may only assign to or destroy a moved-from object (or call members without preconditions, such asclear()). std::exchange(x, v)setsxtovand returns the old value: the idiom for "take and reset".- Taking the assignment parameter by value gives copy and move assignment in one function. The caller's argument decides whether the parameter is copy- or move-constructed, and the swap makes self-assignment safe. The cost is one extra move compared with a hand-written move assignment, which is usually acceptable.
Why noexcept on the move constructor matters
When std::vector outgrows its capacity it allocates a bigger block and relocates every element. It also promises the strong exception guarantee for push_back: if anything throws, the vector is unchanged. Copying the old elements keeps the originals intact if a copy throws; moving them does not. So the library uses std::move_if_noexcept: it moves only if the move constructor is noexcept (or the type is not copyable), and otherwise it copies.
#include <cstdio>
#include <string>
#include <vector>
int copies = 0, moves = 0;
template <bool NoExcept>
struct Order {
std::string id;
explicit Order(std::string s) : id(std::move(s)) {}
Order(const Order& o) : id(o.id) { ++copies; }
Order(Order&& o) noexcept(NoExcept) : id(std::move(o.id)) { ++moves; }
};
template <bool NoExcept>
void run(const char* label) {
copies = moves = 0;
std::vector<Order<NoExcept>> v;
for (int i = 0; i < 1000; ++i) v.emplace_back("ORD" + std::to_string(i));
std::printf("%-18s capacity=%zu copies=%d moves=%d\n", label, v.capacity(), copies, moves);
}
int main() {
run<true>("noexcept move:");
run<false>("throwing move:");
copies = moves = 0;
std::vector<Order<true>> w;
w.reserve(1000);
for (int i = 0; i < 1000; ++i) w.emplace_back("ORD" + std::to_string(i));
std::printf("%-18s capacity=%zu copies=%d moves=%d\n", "reserve(1000):", w.capacity(), copies, moves);
}
Output:
noexcept move: capacity=1024 copies=0 moves=1023
throwing move: capacity=1024 copies=1023 moves=0
reserve(1000): capacity=1000 copies=0 moves=0
Forgetting one keyword turned 1023 cheap moves into 1023 string copies, each a potential heap allocation. Compiler-generated move constructors are noexcept automatically when all members' moves are; a hand-written one is not unless you say so.
Worked example
where do the 1023 relocations come from?
With the output above, explain why 1000 emplace_back calls cause exactly 1023 relocations and a final capacity of 1024, and bound the relocation work for insertions in general.
Show solutionHide solution
This libc++ vector starts at capacity 0 and then doubles: 1, 2, 4, …, 1024. Each time it grows from capacity it relocates the existing elements. Growth happens at sizes (the insertion that would exceed 512 triggers growth to 1024), so the number of relocations is
In general, with doubling the relocations total less than : the geometric sum is dominated by its last term, which is below , and everything before it sums to less than that term. That is why push_back is amortised. The growth factor is implementation-specific (libc++ and libstdc++ double; MSVC grows by 1.5), but the conclusion is the same.
The engineering consequences: make the move constructor noexcept so relocation is cheap, and call reserve when you know the size so it does not happen at all (third line of output: zero relocations).
Copy elision and returning by value
Since C++17, returning a prvalue (return Buffer(n);) constructs the result directly in the caller's storage: no copy or move constructor is called, and none even needs to exist. Returning a named local (Tracer t; return t;) allows named return value optimisation (NRVO), which compilers perform whenever every return returns the same object; if they cannot, the local is treated as an rvalue and moved, never copied.
So return std::move(local); is a pessimisation: it turns the expression into an xvalue, which disables NRVO and forces a move. Clang flags it:
#include <cstdio>
#include <utility>
struct Tracer {
Tracer() = default;
Tracer(const Tracer&) { std::puts("copy"); }
Tracer(Tracer&&) noexcept { std::puts("move"); }
};
Tracer nrvo() { Tracer t; return t; } // named: NRVO (elided in practice)
Tracer pessimised() { Tracer t; return std::move(t); } // blocks NRVO: forces a move
void sink(Tracer&& r) {
Tracer kept = r; // r has a name, so it is an lvalue: copy
Tracer taken = std::move(r); // move
(void)kept; (void)taken;
}
int main() {
const Tracer c;
std::puts("-- std::move on const:");
Tracer x = std::move(c); // const Tracer&& binds to copy ctor
std::puts("-- nrvo:");
Tracer y = nrvo();
std::puts("-- return std::move:");
Tracer z = pessimised();
std::puts("-- named rvalue reference:");
sink(Tracer{});
(void)x; (void)y; (void)z;
}
The compiler warns moving a local object in a return statement prevents copy elision [-Wpessimizing-move], and the program prints:
-- std::move on const:
copy
-- nrvo:
-- return std::move:
move
-- named rvalue reference:
copy
move
The first block is the classic trap: std::move on a const object yields const Tracer&&, which cannot bind to Tracer&& but can bind to const Tracer&, so it silently copies. Never declare a variable const if you intend to move from it.
Worked example
interview question, copy or move?
For each line, say whether s (a std::string member or local) is copied or moved, and why.
void set(std::string name) { name_ = std::move(name); }called asset(local).- The same function called as
set(get_name()), whereget_namereturnsstd::stringby value. void set(const std::string& name) { name_ = std::move(name); }auto v2 = std::move(v1);followed byv1.push_back(1);for astd::vector<int> v1.
Show solutionHide solution
- The parameter is copy-constructed from the lvalue
local(one copy), then moved intoname_. Total: one copy, one move. - The argument is a prvalue, so the parameter is initialised directly from the return value (elided), then moved into
name_. Total: zero copies, one move. This "take by value, then move" idiom is optimal or one move from optimal for both callers, which is why it is the usual recommendation for sink parameters. std::move(name)has typeconst std::string&&, so the copy assignment is chosen. Thestd::moveis misleading noise.v1is moved from: it is valid but unspecified.push_backhas no preconditions, so it is legal; in practice a moved-from vector is empty, but portable code should callv1.clear()first if it relies on that.
The method out loud: identify the value category of each argument expression, then which overload it binds to, then whether elision applies.
Knowledge check
What does std::move(x) do by itself?
Knowledge check
A class with a std::string member has a hand-written move constructor that is not marked noexcept. A std::vector of that class grows from 512 to 1024 elements. What happens to the 512 existing elements?
Knowledge check
Which return statement is best for a local std::vector<int> result?
Key takeaways
- Value category, not type, decides copy versus move. Named things, including named
T&¶meters, are lvalues. std::moveis only a cast. On aconstobject it silently produces a copy.- Moves leave the source valid but unspecified; write move constructors with
std::exchangeso the source is safely empty. - Mark move operations
noexcept, orstd::vectorwill copy on reallocation. Better still, follow the rule of zero and let RAII members generate them. - Return locals by name; never
return std::move(local). Prvalue returns are guaranteed to be elided. - For sink parameters, take by value and
std::moveinto place.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).