Cheat Sheet
- Linux: /linux/
- CLI: /linux/cli/
- locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/
- make: /linux/cli/make/
- awk: /linux/cli/awk/
- find: /linux/cli/find/
- grep: /linux/cli/grep/
- pgrep: /linux/cli/pgrep/
- ps: /linux/cli/ps/
- pstree: /linux/cli/pstree/
- trap: /linux/cli/trap/
- xargs: /linux/cli/xargs/
- Shell: /linux/shell/
- BASH_SOURCE: /linux/shell/bash-source/
- Redirection: /linux/shell/redirection/
- Special Variables: /linux/shell/special-variables/
- Scripting Tips: /linux/shell/script-tips/
- set -o vi: /linux/shell/bash-vi-mode/
- Shell Processing Order: /linux/shell/process-order/
- What are Interactive and Login Shells?: /linux/shell/interactive-login/
- Double Quote Expansion: /linux/shell/shell-expansion/
- System Programming: /linux/system-programming/
- File I/O: /linux/system-programming/file-io/
- Process: /linux/system-programming/process/
- Shared Libraries: /linux/system-programming/shared-libraries/
- Kernel: /linux/kernel/
- Go: /programming/go/
- Concurrency: /programming/go/concurrency/
- CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/
- Channel: /programming/go/concurrency/channel/
- Select: /programming/go/concurrency/select/
- sync: /programming/go/concurrency/sync/
- Concurrency Patterns: /programming/go/concurrency/patterns/
- Goroutines and the Go Runtime: /programming/go/concurrency/runtime/
- Standard Library: /programming/go/std/
- os: /programming/go/std/os/
- context: /programming/go/std/context/
- io: /programming/go/std/io/
- json: /programming/go/std/json/
- net/http: /programming/go/std/net-http/
- slog: /programming/go/std/slog/
- testing: /programming/go/std/testing/
- time: /programming/go/std/time/
- Ellipsis (...): /programming/go/ellipsis/
- error: /programming/go/error/
- Function: /programming/go/function/
- Go Tool: /programming/go/tool/
- Interface: /programming/go/interface/
- Map: /programming/go/map/
- Package and Module: /programming/go/package-module/
- Pointer: /programming/go/pointer/
- Slice: /programming/go/slice/
- String: /programming/go/string/
- Switch: /programming/go/switch/
- Comparison: /programming/go/comparison/
- defaultdict: /programming/python/collections/defaultdict/
- heapq: /programming/python/collections/heapq/
- @cache: /programming/python/cache/
- abc: /programming/python/abc/
- bisect: /programming/python/bisect/
- Type Hints: /programming/python/type-hints/
- Passing Mechanism: /programming/python/passing-mechanism/
- uv: /programming/python/uv/
- *args and **kwargs: /programming/python/args-kwargs/
- re: /programming/python/re/
- C: /programming/c/
- Pointers and Arrays: /programming/c/pointer/
- Syntax Basics: /programming/c/syntax-basics/
- static: /programming/c/static/
- Bit Manipulation: /programming/c/bit-manipulation/
- C vs C++: /programming/c/c-vs-cpp/
- stdatomic: /programming/c/stdatomic/
- C++: /programming/cpp/
- RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/
- Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/
- Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/
- C++ Keywords Reference: /programming/cpp/keywords/
- C++ Primer: /programming/cpp/primer/
- Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/
- Expressions: /programming/cpp/primer/expressions/
- Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/
- Statements: /programming/cpp/primer/statements/
- Functions: /programming/cpp/primer/functions/
- Classes: /programming/cpp/primer/classes/
- The IO Library: /programming/cpp/primer/io-library/
- STL: /programming/cpp/primer/stl/
- Lambda Expressions: /programming/cpp/primer/lambda/
- Smart Pointers: /programming/cpp/primer/smart-pointers/
- Copy Control: /programming/cpp/primer/copy-control/
- Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/
- Object-Oriented Programming (OOP): /programming/cpp/primer/oop/
- Templates and Generic Programming: /programming/cpp/primer/templates/
- Namespaces: /programming/cpp/primer/namespaces/
- Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/
- Advanced: /programming/cpp/advanced/
- Error Handling: /programming/cpp/advanced/error-handling/
- Concurrency & Threading: /programming/cpp/advanced/concurrency/
- Unit Testing: /programming/cpp/advanced/unit-testing/
- Comparison: /programming/comparison/
- Kubernetes: /cloud-devops/kubernetes/
- Fleet: /cloud-devops/kubernetes/gke/fleet/
- Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/
- API Extension: /cloud-devops/kubernetes/api-extension/
- Concept: /cloud-devops/kubernetes/kueue/concept/
- DRA: /cloud-devops/kubernetes/dra/
- Secret Manager: /cloud-devops/terraform/google-secret-manager/
- Knowledge: /network/knowledge/
- PDU: /network/knowledge/osi-model/
- curl: /network/cli/curl/
- Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/
- Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/
- Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/
- Regular Expression: /cs/regular-expression/
- Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/
- Driver and Runtime: /ai-ml/gpu/driver-and-runtime/
- Serving: /ai-ml/serving/
- Dotfiles: /dotfiles/
- Git: /dotfiles/git/
- Cheat Sheet: /dotfiles/git/cheat-sheet/
- revisions: /dotfiles/git/revisions/
- Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/
- checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/
- rebase: /dotfiles/git/rebase/
- Branching and Merging: /dotfiles/git/branching-merging/
- Vim: /dotfiles/vim/
- Plugin: /dotfiles/vim/plugin/
- auto-pairs: /dotfiles/vim/plugin/auto-pairs/
- vim-commentary: /dotfiles/vim/plugin/vim-commentary/
- vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/
- vim-surround: /dotfiles/vim/plugin/vim-surround/
- Marks: /dotfiles/vim/tips/marks/
- vimrc: /dotfiles/vim/vimrc/
- lf: /dotfiles/lf/
# Copy Elision & Move Semantics
{{< katex />}}
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 `delete`s 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:
1. **Applies Only During Initialization (First Creation):**
- When overwriting an **already-existing object via assignment (`y = x;`)** or **reallocating elements inside `std::vector` during growth**, both objects already live at separate addresses and cannot retroactively share storage.
2. **Requires Complete Inaccessibility of the Source Afterward:**
- Simply observing *"the variable name `x` isn't mentioned again later in this function"* is **not strong enough** to merge `x` and `y`! If a compiler merged ordinary named objects `x` and `y` into one address, it could break **the fundamental illusion that they are distinct objects**:
- **Aliasing / Multithreading:** If `&x` was handed to another thread before `std::string y = x;`, mutating `*(&x)` on that background thread would silently corrupt `y`!
- **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).
> **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 ──> nullptr`
`moved.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**:
```cpp
#include
#include
#include
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 CollectTags(int count) {
std::vector 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 input) {
tags_.swap(input); // (6) O(1) swap of internal buffer pointers between 'input' and 'tags_' (0 copies)
}
private:
std::vector 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 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:
1. **Return Local Variables by Value:**
- Do not return heap pointers (`new`) or use output parameters (`std::vector* out`) out of fear of copying a large `std::vector`. Thanks to **Copy Elision (RVO/NRVO)**, `tags` is constructed directly inside the caller's destination slot at **zero cost**.
2. **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 taking `const T&` and copying into the member: moving the copy operation from the function body to the **callsite** makes Copy Elision / Move optimization possible:
| 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()`
1. **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.
2. **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::move` prevents 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::move` is still unnecessary because C++ automatically performs an **implicit move** on the returned variable ([`class.copy.elision`](http://eel.is/c++draft/class.copy.elision)):
1. **Returning different local variables across branches (`if (c) return a; return b;`):** Because both `a` and `b` must exist before the branch is chosen, both cannot be pre-allocated inside the caller's single return slot.
2. **Returning a by-value function parameter (`Widget f(Widget param) { return param; }`):** `param` is already constructed in the caller's argument slot (stack) before the function body begins, physically separate from the caller's return slot.
3. **Returning a local variable of a different type (`Widget w; return w;` when returning `std::optional` or a base type):** Because the types have different memory layouts, they cannot share a slot and a converting move constructor runs automatically.
- **Counterproductive or redundant case ② (`std::move(MakeFoo())`):**
- In `Foo x = std::move(MakeFoo());`, wrapping the temporary inhibits mandatory C++17 RVO (`-Wpessimizing-move`); and because `std::move` simply means *"treat this expression as a temporary (rvalue),"* applying it to something already temporary is redundant (`-Wredundant-move`).
3. **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 as `std::unique_ptr`, guaranteed to become `nullptr`).
4. **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()`.
```cpp
#include
#include
#include
std::vector BuildBatch(int n) {
std::vector 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]({{< relref "/programming/cpp/primer/expressions.md#lvalues-and-rvalues" >}})):
1. **`T&` (lvalue reference, early C++):** Binding `T&` 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 `;`).
2. **`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 being `const`, it could not mutate the temporary to steal its pointer**.
3. **`T&&` (rvalue reference, C++11):** Binds exclusively to rvalues in a **mutable (non-`const`)** state with lifetime extension, enabling `T(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) |
```cpp
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]({{< relref "/programming/cpp/primer/expressions.md#core-distinction-expression-vs-variable-vs-object" >}})):
```cpp
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 `` moves zero bytes itself, it **unconditionally casts `x` to an rvalue reference (`static_cast(x)`)**:
- This lets overload resolution pick `Foo(Foo&&)` over `Foo(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, `` provides two distinct casts:
| Utility (``) | Behavior | Primary Use Case |
| :--- | :--- | :--- |
| **`std::move(x)`** | **Unconditional cast:** always casts `x` to rvalue (`static_cast(x)`) | Explicitly transfer ownership when `x` is no longer needed |
| **`std::forward(x)`** | **Conditional cast:** casts to rvalue only if the original argument was an rvalue; keeps lvalue otherwise | **Perfect Forwarding** in template wrappers (`template void f(T&& x)`) (see [Templates: Forwarding References & Reference Collapsing]({{< relref "/programming/cpp/primer/templates.md#forwarding-references-t-and-reference-collapsing-rules" >}})) |
```cpp
void Target(const std::string &s); // (1) lvalue overload (copy)
void Target(std::string &&s); // (2) rvalue overload (move)
template
void Wrapper(T &&arg) { // T&& is a forwarding reference
Target(arg); // Always calls (1): expression 'arg' is a named variable (lvalue)!
Target(std::forward(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]({{< relref "/programming/cpp/primer/copy-control.md#4-the-rule-of-three--five--zero" >}}), see [Copy Control]({{< relref "/programming/cpp/primer/copy-control.md#3-deep-copy-and-self-assignment-safety" >}}):
### 1. Leave the Source in a Valid State (`nullptr`, etc.)!
- In `HasPtr`'s move constructor and move assignment operator below, after stealing the pointer via `this->ps = rhs.ps;`, you **must** set `rhs.ps = nullptr;` so that when `~HasPtr()` later runs on `rhs`, it executes `delete nullptr;` instead of freeing your stolen buffer!
- **Use `= default` Judiciously:** For simple `struct`s 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)` in `operator=` below prevents `x = std::move(x);` from deleting `ps` before reading it.
### 3. Always Mark Both Declaration and Definition `noexcept`!
- **Strong Exception Safety & `std::move_if_noexcept`:**
- When `std::vector` reallocates 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 marked `noexcept`: and silently falling back to slow deep copies if `noexcept` is omitted!**
```cpp
#include
#include
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:
1. **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::value()`, overloading on `const &` vs. `&&` returns a read-only reference on live lvalue objects while moving `body_` out of expiring rvalue temporaries with zero copies.
2. **Single-Use Sink / Builder Methods (`PacketBuilder::Build() &&` only):**
- Declaring only the `&&` overload (`PacketBuilder::Build() &&` below) forces callers to write `std::move(builder).Build()`, catching accidental post-build reuse of the consumed builder at compile time.
```cpp
#include
#include
#include
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 buf_;
public:
void Append(char c) { buf_.push_back(c); }
std::vector 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
}
```