Copy Elision & Move Semantics#
This guide traces the full story of Copy Elision and Move Semantics in Modern C++ (C++11+): why Copy Elision alone could not solve every copy overhead, how Move Semantics fills that exact gap, practical rules of thumb (single-live-name intuition, parameter/return API guidelines, and std::move best practices), language mechanics (T& -> const T& -> T&&, std::move vs. std::forward), implementing noexcept move operations, and ref-qualified member functions (& / &&).
1. Historical Context & Big Picture: Copy -> Copy Elision -> Move Semantics#
1. The Starting Problem: Wasteful Deep Copies#
Value semantics in C++ treat objects as independent values by default. Without optimization, initializing or assigning from an expiring temporary, or handing off a local object that will never be used again, allocates a brand-new heap buffer (new), copies all $N$ elements ($O(N)$), and immediately deletes the source buffer.
2. First Solution: Copy Elision (RVO / NRVO, Cost 0)#
Even before C++11, compilers eliminated many copies via Copy Elision: treating the source and destination as occupying the exact same memory slot from the start, skipping both the copy/move constructor and the extra destructor call.
Instead of constructing a temporary inside the callee and copying it out to the caller, the caller passes the destination memory address to the callee up front so the callee constructs the result directly in the caller’s target location, completely eliminating both the intermediate copy/move constructor and destructor call:
| Variant | RVO (Unnamed Return Value Optimization) | NRVO (Named Return Value Optimization) |
|---|---|---|
| Where It Applies | Returning/initializing from nameless temporaries (return Widget(1, 2);, Widget w = Make();) | Returning a single named local variable (Widget w; ... return w;) |
| Standard Guarantee | Mandatory guarantee since C++17 (language rule, not optional) | Optional optimization (performed reliably by gcc, clang, msvc) |
| When Inhibited | Never (since C++17) | 1. Returning different named locals across branches (if (c) return a; else return b;)2. Anti-pattern return std::move(w); (turns expression into T&&, preventing NRVO, triggers -Wpessimizing-move) |
3. Two Hard Limits of Copy Elision (Why Move Semantics Was Invented)#
Because Copy Elision literally merges two objects into one storage location, it hits two fundamental constraints that it can never cross:
- Applies Only During Initialization (First Creation):
- When overwriting an already-existing object via assignment (
y = x;) or reallocating elements insidestd::vectorduring growth, both objects already live at separate addresses and cannot retroactively share storage.
- When overwriting an already-existing object via assignment (
- Requires Complete Inaccessibility of the Source Afterward:
- Simply observing “the variable name
xisn’t mentioned again later in this function” is not strong enough to mergexandy! If a compiler merged ordinary named objectsxandyinto one address, it could break the fundamental illusion that they are distinct objects:- Aliasing / Multithreading: If
&xwas handed to another thread beforestd::string y = x;, mutating*(&x)on that background thread would silently corrupty! - Visible Destructor Side-Effects: Merging two live objects into one would run the destructor once instead of twice, altering observable behavior (locks, files, logging, reference counts).
- Aliasing / Multithreading: If
- Simply observing “the variable name
Why Move Semantics Exists: Whenever those constraints block Copy Elision (assignment, container reallocation, or transferring value out of a named local variable), Move Semantics (C++11) provides the second tier: keeping two distinct objects while transferring ownership of internal heap pointers in $O(1)$ time instead of paying an $O(N)$ deep copy!
4. The Compiler’s Automatic 3-Tier Priority#
| Priority Tier | Mechanism | Memory / Pointer State | Constructor Calls & Cost |
|---|---|---|---|
| 1st Tier: Copy Elision (RVO / NRVO) | Construct 1 object directly in the caller’s destination slot | dest (== src) ──> [ "hello..." ] | 0 copy/move ctor calls Cost 0 |
| 2nd Tier: Move (Move Ctor / Assign) | 2 distinct objects; transfer internal buffer pointer and null out source | orig.ptr ──> nullptrmoved.ptr ─> [ "hello..." ] | 1 move ctor call Cost $O(1)$ |
| 3rd Tier: Deep Copy (Copy Ctor / Assign) | Allocate new heap buffer (new) and copy all $N$ elements | orig.ptr ──> [ "hello..." ]copy.ptr ──> [ "hello..." ] | 1 copy ctor call Cost $O(N)$ |
2. Practical Rules of Thumb for Avoiding Unnecessary Copies (Copy Elision & Move)#
1. How to Tell When a Copy Runs: The Distinct-Names Rule#
A simple intuition tells immediately whether code that looks like copying actually invokes a 3rd-tier copy constructor:
Distinct-Names Rule
An initialization or assignment invokes a copy constructor only when two or more live variable names must independently own that value at the same time afterward.
For example, when tracing TagHolder h1(CollectTags(n)); in the code below, each string passes through tag -> (unnamed return value) -> tags[i] -> input[i] -> h1.tags_[i], never holding more than one live variable name at any point in time. Because ownership is simply handed off at each step, Copy Elision and Move Semantics combine to produce 0 std::string copy constructor calls:
#include <string>
#include <utility>
#include <vector>
std::string BuildTag(int id) {
if (id % 2 == 0) {
std::string tag("even");
return tag; // (1) Distinct return paths prevent NRVO -> 2nd-tier Move (0 copies)
} else {
return std::string("odd"); // (1') Unnamed temporary return -> mandatory C++17 RVO (0 copies, 0 moves)
}
}
std::vector<std::string> CollectTags(int count) {
std::vector<std::string> tags;
for (int i = 0; i < count; ++i) {
// (2) rvalue arg -> calls push_back(std::string&&) move overload (0 copies)
// (3) Vector resize -> std::string move constructor is noexcept, so elements move (0 copies)
tags.push_back(BuildTag(i));
}
return tags; // (4) Single local variable -> NRVO (or O(1) move of vector's internal buffer pointer, 0 element copies)
}
class TagHolder {
public:
// (5) Pass-by-value parameter (input):
// - Passed an rvalue (temporary): constructs 'input' via Copy Elision (or O(1) Move) -> 0 element copies
// - Passed an lvalue (named variable): calls vector's copy constructor to preserve caller's original!
explicit TagHolder(std::vector<std::string> input) {
tags_.swap(input); // (6) O(1) swap of internal buffer pointers between 'input' and 'tags_' (0 copies)
}
private:
std::vector<std::string> tags_;
};
void Demo(int n) {
// ✅ 1. Pass rvalue: (5) constructs 'input' via Copy Elision -> (6) O(1) swap -> 0 total copies!
TagHolder h1(CollectTags(n));
// ❌ 2. Pass lvalue: to keep 'saved' intact after the call,
// initializing parameter 'input' at (5) invokes vector's copy constructor -> n deep copies!
std::vector<std::string> saved = CollectTags(n);
TagHolder h2(saved);
// ✅ 3. Relinquish old name 'saved' via std::move:
// (5) initializes parameter 'input' via vector's O(1) move constructor -> back to 0 element copies!
TagHolder h3(std::move(saved));
}2. Two Function Design Rules for Taking Advantage of Copy Elision (RVO)#
The two major cases where Copy Elision occurs (returning a local variable from a function, and initializing a variable or by-value parameter from a temporary) lead directly to two function design rules:
Return Local Variables by Value:
- Do not return heap pointers (
new) or use output parameters (std::vector<T>* out) out of fear of copying a largestd::vector. Thanks to Copy Elision (RVO/NRVO),tagsis constructed directly inside the caller’s destination slot at zero cost.
- Do not return heap pointers (
If You Need to Make a Copy of a Function Parameter, Accept It by Value:
- Read-only parameters that are not copied should still be taken by
const T&(0 copies). - Given that initializing a parameter from a temporary triggers Copy Elision, when a function/constructor must store its own copy anyway (like
TagHolder), taking the parameter by value (T) and moving/swapping it into place is better than takingconst T&and copying into the member: moving the copy operation from the function body to the callsite makes Copy Elision / Move optimization possible:
- Read-only parameters that are not copied should still be taken by
| Constructor Signature Design | lvalue Arg (TagHolder h(saved);) | rvalue Arg (TagHolder h(CollectTags(n));) |
|---|---|---|
TagHolder(const vector& input){ tags_ = input;} | 1 deep copy at tags_ = input | input is const& (cannot move) -> 1 deep copy at tags_ = input |
TagHolder(vector input){ tags_.swap(input);} | 1 deep copy at callsite (input = saved) + $O(1)$ swap | Copy Elision at callsite + $O(1)$ swap -> 0 deep copies |
3. Four Rules of Thumb for Using std::move()#
- Use
std::move()When Code Won’t Compile Without It (std::unique_ptr, Move-Only Types):- When transferring a move-only object triggers a copy-constructor compile error, wrap the source in
std::move(ptr)to permit the move explicitly.
- When transferring a move-only object triggers a copy-constructor compile error, wrap the source in
- Use
std::move()Selectively for Local Optimizations: Avoid It Where Elision Applies:- Where it helps: Wrap a local variable on its final use when its type owns heap memory and has a cheap move constructor (
std::string,std::vector, serialized message objects; moving plain scalars or trivial structs brings no benefit). - Counterproductive or redundant case ① (
return std::move(local);):- When NRVO applies (
-Wpessimizing-move): When returning a single local variable of the exact return type (Widget w; return w;),std::moveprevents zero-cost Copy Elision and forces an extra move constructor call instead. - When NRVO cannot apply (
-Wredundant-move): Even when the returned variable cannot physically share the caller’s return slot via NRVO,std::moveis still unnecessary because C++ automatically performs an implicit move on the returned variable (class.copy.elision):- Returning different local variables across branches (
if (c) return a; return b;): Because bothaandbmust exist before the branch is chosen, both cannot be pre-allocated inside the caller’s single return slot. - Returning a by-value function parameter (
Widget f(Widget param) { return param; }):paramis already constructed in the caller’s argument slot (stack) before the function body begins, physically separate from the caller’s return slot. - Returning a local variable of a different type (
Widget w; return w;when returningstd::optional<Widget>or a base type): Because the types have different memory layouts, they cannot share a slot and a converting move constructor runs automatically.
- Returning different local variables across branches (
- When NRVO applies (
- Counterproductive or redundant case ② (
std::move(MakeFoo())):- In
Foo x = std::move(MakeFoo());, wrapping the temporary inhibits mandatory C++17 RVO (-Wpessimizing-move); and becausestd::movesimply means “treat this expression as a temporary (rvalue),” applying it to something already temporary is redundant (-Wredundant-move).
- In
- Where it helps: Wrap a local variable on its final use when its type owns heap memory and has a cheap move constructor (
- Never Trust an Object’s Value After Calling
std::move()on It:- A moved-from object is left in a valid but unspecified state: safe to destroy or reassign (
x = ...), unsafe to read unless the type explicitly specifies its post-move state (such asstd::unique_ptr, guaranteed to becomenullptr).
- A moved-from object is left in a valid but unspecified state: safe to destroy or reassign (
- Count Simultaneous Live Names:
- Whenever creating a new name for a value whose previous name is no longer needed, relinquish the old name with
std::move().
- Whenever creating a new name for a value whose previous name is no longer needed, relinquish the old name with
#include <string>
#include <utility>
#include <vector>
std::vector<std::string> BuildBatch(int n) {
std::vector<std::string> batch;
batch.reserve(n);
for (int i = 0; i < n; ++i) {
std::string entry = "row_" + std::to_string(i);
batch.push_back(std::move(entry)); // ✅ Last use of 'entry' in loop -> Move eliminates copy!
}
return batch; // ✅ Return as-is so NRVO (cost 0) applies; std::move(batch) inhibits NRVO (-Wpessimizing-move)
}3. Evolution of Reference Types & Binding Rules (T& -> const T& -> T&&)#
For overload resolution to distinguish automatically between “an lvalue that must keep its value” and “an expiring rvalue whose resources can be stolen,” C++ references evolved across three historical stages (see Expressions: lvalues and rvalues):
T&(lvalue reference, early C++): BindingT&to temporaries was banned to prevent silent mutations of discarded temporaries and dangling reference UB (int &r = 42; r = 100;would write to a temporary destroyed at;).const T&(const lvalue reference, C++98): Allowed read-only binding to temporaries with lifetime extension through the reference’s scope, eliminating argument copies, but beingconst, it could not mutate the temporary to steal its pointer.T&&(rvalue reference, C++11): Binds exclusively to rvalues in a mutable (non-const) state with lifetime extension, enablingT(T&&)move overloads.
| Reference Type | Syntax | Standard | Binds lvalue? | Binds const lvalue? | Binds rvalue? | Mutable Target? | Primary Role |
|---|---|---|---|---|---|---|---|
| Lvalue Reference | T& | C++98 | ✅ | ❌ | ❌ | ✅ | Mutate existing non-const object |
| Const Lvalue Reference | const T& | C++98 | ✅ | ✅ | ✅ (lifetime ext.) | ❌ | Copy operations & read-only params |
| Rvalue Reference | T&& | C++11 | ❌ | ❌ | ✅ (lifetime ext.) | ✅ | Move operations (resource theft) |
int &r1 = 42; // ❌ Compile error: non-const T& cannot bind to rvalue
const int &r2 = 42; // ✅ Valid (C++98): extends temporary lifetime (read-only)
int &&r3 = 42; // ✅ Valid (C++11): extends temporary lifetime + mutable!
Key Pitfall: “A Named Variable of Type T&& Is Still an lvalue Expression!”#
Even when declared with type T&&, any named variable has persistent identity throughout its scope, so writing its name in an expression always evaluates as an lvalue (for the distinction between a variable’s declared type and an expression’s value category, see Expressions: Expression vs. Variable vs. Object):
int &&rr1 = 42; // Valid: 42 is an rvalue (lifetime extended)
rr1 = 100; // ✅ Valid: expression 'rr1' is a mutable lvalue
// int &&rr2 = rr1; // ❌ Compile error! Named variable expression 'rr1' is an lvalue!
int &&rr3 = std::move(rr1); // ✅ Valid: std::move casts 'rr1' back to an xvalue
4. How std::move and std::forward Work Under the Hood#
1. std::move(x) Is Purely a Type Cast!#
std::move(x) in <utility> moves zero bytes itself, it unconditionally casts x to an rvalue reference (static_cast<T&&>(x)):
- This lets overload resolution pick
Foo(Foo&&)overFoo(const Foo&). - If a type provides only a copy constructor and no move constructor,
const Foo&binds to rvalues and safely falls back to copying.
2. std::move vs. std::forward (Move Semantics vs. Perfect Forwarding)#
Because named parameters inside a function body are always lvalues, <utility> provides two distinct casts:
Utility (<utility>) | Behavior | Primary Use Case |
|---|---|---|
std::move(x) | Unconditional cast: always casts x to rvalue (static_cast<T&&>(x)) | Explicitly transfer ownership when x is no longer needed |
std::forward<T>(x) | Conditional cast: casts to rvalue only if the original argument was an rvalue; keeps lvalue otherwise | Perfect Forwarding in template wrappers (template <typename T> void f(T&& x)) (see Templates: Forwarding References & Reference Collapsing) |
void Target(const std::string &s); // (1) lvalue overload (copy)
void Target(std::string &&s); // (2) rvalue overload (move)
template <typename T>
void Wrapper(T &&arg) { // T&& is a forwarding reference
Target(arg); // Always calls (1): expression 'arg' is a named variable (lvalue)!
Target(std::forward<T>(arg)); // Calls (1) for lvalue args; calls (2) for rvalue args!
}5. Implementing Move Constructors & Move Assignment Operators#
When a class manages dynamic memory directly, follow these three essential rules when implementing move operations. For the corresponding copy constructor and copy assignment operator under the Rule of Three / Five, see Copy Control:
1. Leave the Source in a Valid State (nullptr, etc.)!#
- In
HasPtr’s move constructor and move assignment operator below, after stealing the pointer viathis->ps = rhs.ps;, you must setrhs.ps = nullptr;so that when~HasPtr()later runs onrhs, it executesdelete nullptr;instead of freeing your stolen buffer! - Use
= defaultJudiciously: For simplestructs or Rule-of-Zero classes composed purely of RAII members, default move operations are ideal. However, if a class requires consistency across multiple members or owns raw pointers, memberwise default move can break that consistency, so write both move constructor and move assignment together as a pair.
2. Check for Self-Assignment (this != &rhs) in Move Assignment!#
- Guarding
if (this != &rhs)inoperator=below preventsx = std::move(x);from deletingpsbefore reading it.
3. Always Mark Both Declaration and Definition noexcept!#
- Strong Exception Safety &
std::move_if_noexcept:- When
std::vectorreallocates to grow capacity, throwing midway through moving elements would leave already-moved source elements mutated, violating the strong exception guarantee. - Standard containers therefore query
std::move_if_noexcept, invoking your fast move constructor only if markednoexcept: and silently falling back to slow deep copies ifnoexceptis omitted!
- When
#include <string>
#include <utility>
class HasPtr {
private:
std::string *ps;
int i;
public:
HasPtr(const std::string &s = std::string())
: ps(new std::string(s)), i(0) {}
// (Copy constructor & copy assignment operator omitted for brevity under Rule of 3/5)
// 1. Move Constructor (noexcept required!)
HasPtr(HasPtr &&rhs) noexcept : ps(rhs.ps), i(rhs.i) {
rhs.ps = nullptr; // Essential! Prevents ~HasPtr() on rhs from freeing our stolen buffer
}
// 2. Move Assignment Operator (noexcept required!)
HasPtr& operator=(HasPtr &&rhs) noexcept {
if (this != &rhs) {
delete ps; // (1) Free existing heap memory
ps = rhs.ps; // (2) Steal ownership of rhs's pointer
i = rhs.i;
rhs.ps = nullptr; // (3) Leave rhs in a valid empty state
}
return *this;
}
~HasPtr() { delete ps; }
};6. Ref-qualified Member Functions#
In a class’s member function, just as const after () qualifies *this’s constness, reference qualifiers (& and &&) restrict or overload member functions based on whether the receiver *this is an lvalue or an rvalue. They appear after () and immediately after const (before noexcept).
| Member Declaration | Allowed Receiver (*this) | Example (Widget w;) |
|---|---|---|
memberFunc(); (omitted) | Both lvalue and rvalue | w.memberFunc(); ✅ / Widget().memberFunc(); ✅ |
memberFunc() &; | lvalue objects only | w.memberFunc(); ✅ / Widget().memberFunc(); ❌ |
memberFunc() &&; | rvalue objects only (temporaries, std::move) | w.memberFunc(); ❌ / Widget().memberFunc(); ✅ / std::move(w).memberFunc(); ✅ |
Overloading Rule: If any overload with the same name and parameter list carries a ref-qualifier (
&or&&), every overload with that parameter list must carry one.
Two Essential Real-World Patterns#
Using the Response and PacketBuilder classes in the code below:
- Getter Overloading (
Response::body():const &borrow vs.&&buffer theft):- Because a member variable (
body_) already lives inside the object rather than being newly created inside the getter, Copy Elision (NRVO) cannot apply when returning it. - Following the standard pattern used by
std::optional<T>::value(), overloading onconst &vs.&&returns a read-only reference on live lvalue objects while movingbody_out of expiring rvalue temporaries with zero copies.
- Because a member variable (
- Single-Use Sink / Builder Methods (
PacketBuilder::Build() &&only):- Declaring only the
&&overload (PacketBuilder::Build() &&below) forces callers to writestd::move(builder).Build(), catching accidental post-build reuse of the consumed builder at compile time.
- Declaring only the
#include <string>
#include <utility>
#include <vector>
class Response {
private:
std::string body_;
public:
explicit Response(std::string b) : body_(std::move(b)) {}
const std::string& body() const & noexcept { return body_; }
std::string body() && noexcept { return std::move(body_); }
};
class PacketBuilder {
private:
std::vector<char> buf_;
public:
void Append(char c) { buf_.push_back(c); }
std::vector<char> Build() && noexcept { return std::move(buf_); }
};
void usage(Response Fetch()) {
Response res("large payload");
const std::string &view = res.body(); // Calls const & overload (preserves res)
std::string stolen1 = std::move(res).body(); // Calls && overload (0 copies)
std::string stolen2 = Fetch().body(); // Calls && overload (steals temporary buffer)
PacketBuilder builder;
builder.Append('A');
// auto pkt = builder.Build(); // ❌ Compile error! Cannot call && on lvalue
auto pkt = std::move(builder).Build(); // ✅ OK: explicitly signals consumption
}