# Copy elision and NRVO

> Why C++17 guaranteed prvalue elision eliminates moves by language semantics rather than optimization, and how optional NRVO breaks when you write return std::move(x).

- **Source:** C++ Atlas (https://cppatlas.com/topics/copy-elision)
- **Track:** Value semantics
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [class.copy.elision] (https://eel.is/c++draft/class.copy.elision), [basic.lval] (https://eel.is/c++draft/basic.lval), [conv.rval] (https://eel.is/c++draft/conv.rval), [dcl.init] (https://eel.is/c++draft/dcl.init), [expr.call] (https://eel.is/c++draft/expr.call)
- **cppreference links:** [Copy elision](https://en.cppreference.com/w/cpp/language/copy_elision), [Value categories](https://en.cppreference.com/w/cpp/language/value_category), [return statement](https://en.cppreference.com/w/cpp/language/return), [Copy-initialization](https://en.cppreference.com/w/cpp/language/copy_initialization), [Direct-initialization](https://en.cppreference.com/w/cpp/language/direct_initialization)
- **Prerequisites:** value-categories, copy-and-move

Copy elision began in C++98 as a compiler permission slip: the compiler could skip calling a copy constructor when constructing from a temporary, yet the language still forced that copy constructor to exist and be accessible. C++17 split that single rule into two fundamentally different mechanisms: **guaranteed prvalue initialization**, where no copy or move ever exists in the abstract machine, and **optional elision** such as NRVO, where a real local object's construction may still be fused into the caller's destination.

## From compiler optimization to language guarantee

Prior to C++17, returning a `std::mutex` or non-movable lock guard by value from a factory function failed to compile. Even when `-O2` elided every copy instruction in machine code, the front-end checked whether an accessible copy or move constructor existed before eliding it.

C++17 fixed this by redefining **prvalues** (`[basic.lval]`, `[dcl.init]`). Because a prvalue is an unmaterialized initializer rather than an object in storage, returning `T{args...}` passes the initialization recipe directly down to the caller's target object slot.

> **Mental model.** Guaranteed copy elision does not delete a move constructor call—it passes the destination memory address down the prvalue chain so only one object is ever constructed.

## Mandatory prvalue elision in C++17 and beyond

Under `[dcl.init]` and `[conv.rval]`, whenever an object of class type `T` is initialized from a prvalue whose cv-unqualified type is also `T`, no temporary object is materialized at all. You can chain arbitrarily many factory functions returning by value, pass prvalues into value parameters (`take(make())`), or allocate via `new T(make())`, and none of them require a copy or move constructor:

```cpp
struct NonMovable {
    int token;
    explicit NonMovable(int t) : token(t) {}
    NonMovable(const NonMovable&) = delete;
    NonMovable(NonMovable&&) = delete;
};

NonMovable make_inner() { return NonMovable{42}; }
NonMovable make_outer() { return make_inner(); }
void consume(NonMovable nm) { (void)nm.token; }

void mandatory_elision_demo() {
    NonMovable direct = make_outer(); // Constructs directly into `direct`
    consume(make_outer());            // Constructs directly into parameter `nm`
    (void)direct;
}
```

Four boundaries mark where mandatory prvalue elision **stops** applying:

- **Assignment (`target = make_outer();`)**: `target` is already alive, so `make_outer()` materializes a temporary xvalue and invokes `operator=`.
- **Type mismatch (`Base b = make_derived();`)**: When the destination type differs from the prvalue's type, materialization occurs to construct `Derived` and then `Base(Derived&&)` (object slicing) runs.
- **Returning a named variable (`return local;`)**: `local` is an lvalue, not a prvalue, shifting the situation from mandatory elision to optional NRVO.
- **No-unique-address members or base subobjects**: Initializing a base subobject or a `[[no_unique_address]]` member from a prvalue may still materialize a temporary on some ABIs because tail padding can overlap sibling data.

> **Standardese.** Under `[dcl.init]`, when initializing an object of class type from a prvalue of the same cv-unqualified class type, the initializer expression directly initializes the target object without materializing a temporary.

## NRVO and optional compiler elision

When a function constructs a **named** automatic local object and returns it (`return buf;`), that object already owns storage in the function's stack frame unless the compiler places `buf` directly in the caller's return-value slot. That transformation is **Named Return Value Optimization (NRVO)** (`[class.copy.elision]`).

| Mechanism | Applies to | Copy or move ctor required? | Guaranteed by ISO C++? | Observable ctor/dtor side effects skipped? |
| --- | --- | --- | --- | --- |
| Mandatory prvalue init | Unnamed prvalue of same cv-unqualified type | No (even if `= delete`) | Yes (C++17+) | Yes, no extra object exists |
| NRVO | Named local automatic object of same return type | Yes, must be accessible | No (permitted only) | Yes, when compiler applies NRVO |
| Implicit move | Named local or parameter when elision is not used | Yes (rvalue overload first) | Yes (overload order) | No, move ctor runs |

Beyond NRVO, `[class.copy.elision]` permits optional elision in two exception-handling cases: throwing an automatic local variable (`throw err;`) into the exception object, and catching an exception by value (`catch (MyError e)`) directly sharing storage with the active exception object—again, only when a copy or move constructor is accessible.

## What breaks NRVO and how to keep it

Because NRVO is an optional optimization rather than a language guarantee, small structural choices prevent compilers from fusing a local variable into the return slot:

1. **Writing `return std::move(local);`**: NRVO requires the `return` operand to be the unparenthesized name of a non-volatile automatic variable. Wrapping it in `std::move(local)` turns the operand into a function call returning an xvalue, **disabling NRVO** and forcing an actual move constructor call (flagged by `-Wpessimizing-move`).
2. **Returning a function parameter (`return param;`)**: Function parameters reside in caller- or ABI-dictated parameter slots, so `[class.copy.elision]` forbids NRVO on parameters—though implicit move still selects the move constructor.
3. **Returning different local variables on multiple branches (`if (ok) return a; return b;`)**: A single return slot cannot simultaneously alias two distinct live objects `a` and `b`, so compilers usually disable NRVO on at least one branch.
4. **Returning a member subobject or static/global variable (`return pair.first;`)**: Neither is an automatic variable matching the return type's whole storage.

> **Pitfall.** Writing `return std::move(local);` blocks NRVO and forces a runtime move construction where plain `return local;` constructs directly in the caller's slot—and already uses implicit move whenever NRVO cannot run.

## Compilable proof: prvalues vs named locals

Testing `NonMovable` side by side highlights the exact boundary between C++17's language guarantee and optional NRVO:

```cpp
struct NonMovable {
    int id;
    explicit NonMovable(int v) : id(v) {}
    NonMovable(const NonMovable&) = delete;
    NonMovable(NonMovable&&) = delete;
};

NonMovable ok_prvalue(bool flag) {
    if (flag) {
        return NonMovable{1}; // Guaranteed: direct in-place init
    }
    return NonMovable{2};     // Guaranteed: separate prvalue branch
}

/* Ill-formed even though NRVO could optimize it in release builds:
NonMovable broken_nrvo() {
    NonMovable local{3};
    return local; // Error: NonMovable(NonMovable&&) is deleted!
}
*/
```

Even though an optimizing compiler would gladly apply NRVO to `broken_nrvo()`, the standard forbids relying on NRVO for legality because another build configuration (or `-fno-elide-constructors`) must still have a valid move or copy constructor to fall back on. Only when returning an unmaterialized prvalue—even across multiple `if` branches—does C++17 guarantee that no copy or move constructor is ever needed.

## What to remember

- Guaranteed copy elision in C++17+ applies to prvalues of the same cv-unqualified class type and works even when copy and move constructors are `= delete`.
- Assignment (`x = make()`), type mismatches (`Base b = make_derived()`), and named local variables (`return local;`) do not trigger guaranteed prvalue elision.
- NRVO is permitted but never guaranteed, so returned named locals still require an accessible copy or move constructor.
- Never write `return std::move(local);`: it disables NRVO, whereas plain `return local;` gets NRVO when possible and implicit move automatically otherwise.

## Concept Map Outline

- **Copy elision and NRVO:** C++17 separates guaranteed prvalue initialization from optional compiler elision such as NRVO.
  - **Mandatory prvalue elision:** Prvalues are unmaterialized initializers that construct directly inside the destination slot.
    - **No ctor required:** Types with deleted copy and move constructors can still be returned by prvalue.
    - **Chained factory calls:** Nested prvalue returns forward the target slot without creating intermediate objects.
    - **Where it stops:** Assignment, slicing conversions, and named locals still require assignment or ctors.
  - **Optional NRVO:** Compilers may fuse a named automatic local variable directly into the caller return slot.
    - **Accessible ctor needed:** Because NRVO is optional, the returned type must still expose a copy or move constructor.
    - **Throw and catch elision:** The standard also permits eliding copies when throwing locals or catching by value.
  - **What disables NRVO:** Several common patterns prevent the compiler from aliasing a local with the return slot.
    - **return std::move(local):** Casting the returned variable to an xvalue blocks NRVO and forces an explicit move.
    - **Function parameters:** ABI parameter storage forbids NRVO on parameters, though implicit move still applies.
    - **Multiple distinct locals:** Returning different local variables on separate branches usually defeats NRVO.
    - **Members and globals:** Subobjects and non-automatic objects cannot occupy the caller return slot directly.
  - **Implicit move fallback:** When NRVO does not run, plain return local tries rvalue move resolution automatically.
    - **Rvalue-first overload lookup:** Overload resolution tries treating the returned local or parameter as an rvalue first.
    - **C++23 P2266R3 rule:** Simpler implicit move treats move-eligible id-expressions uniformly across return conversions.
    - **Best practice rule:** Write plain return local to preserve NRVO when possible and implicit move otherwise.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init], [basic.lval])

Why does returning `NonMovable{42}` from `NonMovable make()` compile in C++17+ even though both its copy and move constructors are `= delete`?

```cpp
struct NonMovable {
    NonMovable(int);
    NonMovable(const NonMovable&) = delete;
    NonMovable(NonMovable&&) = delete;
};
NonMovable make() { return NonMovable{42}; }
```

A. Because C++17 ignores = delete inside return statements
B. Because NonMovable{42} is a prvalue that directly initializes the caller's target slot without materializing or moving a temporary
C. Because NRVO automatically synthesizes a private move constructor
D. Because return NonMovable{42} calls memcpy on the stack frame

**Answer (B):** Because NonMovable{42} is a prvalue that directly initializes the caller's target slot without materializing or moving a temporary

**Why:** Since C++17 ([basic.lval], [dcl.init]), a prvalue is an unmaterialized initializer rather than a temporary object. Initializing a NonMovable destination from a NonMovable prvalue constructs directly in place with zero copy or move calls.

### Question 2 [warmup] ([class.copy.elision])

What is the practical effect of writing `return std::move(s);` when `s` is a local `std::string` inside `std::string build()`?

```cpp
std::string build() {
    std::string s = "long heap string";
    return std::move(s);
}
```

A. It triggers guaranteed copy elision by converting s into a prvalue
B. It speeds up the function because plain return s would copy s
C. It prevents NRVO and forces a move construction instead of zero-cost in-place construction
D. It causes undefined behavior because s is destroyed before the move finishes

**Answer (C):** It prevents NRVO and forces a move construction instead of zero-cost in-place construction

**Why:** NRVO applies only when the return operand is the plain name of a local automatic variable. std::move(s) turns it into a function call xvalue, disabling NRVO and forcing a move constructor (-Wpessimizing-move).

### Question 3 [tricky] ([class.copy.elision], [dcl.init])

In C++23, which snippet fails to compile when `Token` has deleted copy and move constructors?

```cpp
struct Token {
    explicit Token(int);
    Token(const Token&) = delete;
    Token(Token&&) = delete;
};
```

A. Token a = Token{1};
B. Token make() { return Token{2}; } Token b = make();
C. Token bad() { Token t{3}; return t; }
D. void f(Token); f(Token{4});

**Answer (C):** Token bad() { Token t{3}; return t; }

**Why:** Returning a named local variable t relies on optional NRVO, not guaranteed prvalue elision. Because NRVO is optional under [class.copy.elision], the language still requires an accessible copy or move constructor for t.

### Question 4 [tricky] ([class.copy.elision])

Given `std::string passthrough(std::string param) { return param; }`, what happens in the `return param;` statement?

```cpp
std::string passthrough(std::string param) {
    return param;
}
```

A. Mandatory prvalue elision constructs param directly in the caller's return slot
B. NRVO applies because param is a named variable inside passthrough
C. Copy constructor runs because param is an lvalue
D. NRVO is forbidden on function parameters, so implicit move invokes std::string(std::string&&)

**Answer (D):** NRVO is forbidden on function parameters, so implicit move invokes std::string(std::string&&)

**Why:** Under [class.copy.elision], NRVO excludes function parameters because parameter storage lives in the caller/ABI frame. However, param is move-eligible, so implicit move constructs the return object using std::string's move constructor.

### Question 5 [standardese] ([dcl.init], [conv.rval])

Suppose `Derived` publicly inherits from `Base` and `Derived make_derived();` returns a prvalue. Does `Base b = make_derived();` bypass `Base`'s move constructor via mandatory copy elision?

```cpp
struct Base { Base(const Base&) = delete; Base(Base&&) = delete; };
struct Derived : Base {};
Derived make_derived();
```

A. No; mandatory prvalue elision requires the prvalue's cv-unqualified type to match Base, so make_derived() materializes and fails because Base(Base&&) is deleted
B. Yes; mandatory elision constructs only the Base subobject directly in b
C. Yes, provided Derived adds no data members
D. No; it invokes reinterpret_cast<Base&&>(make_derived())

**Answer (A):** No; mandatory prvalue elision requires the prvalue's cv-unqualified type to match Base, so make_derived() materializes and fails because Base(Base&&) is deleted

**Why:** [dcl.init] grants direct initialization without temporary materialization only when the prvalue has the same cv-unqualified class type as the destination object. When constructing Base from a Derived prvalue, Derived materializes via [conv.rval] and Base's deleted move constructor makes the initialization ill-formed.

### Question 6 [standardese] ([conv.rval], [dcl.init])

Which statement about `x = make_widget();` (copy assignment to an already-constructed `Widget x`) is accurate under C++23?

```cpp
struct Widget {};
Widget make_widget();
void assign() {
    Widget x;
    x = make_widget();
}
```

A. Mandatory copy elision constructs the return value of make_widget() directly on top of x without calling operator=
B. make_widget() undergoes temporary materialization conversion ([conv.rval]) to an xvalue, and Widget::operator=(Widget&&) (or const Widget&) is called
C. x is automatically destroyed and placement-newed via NRVO
D. Assignment to an existing object is ill-formed if make_widget() returns a prvalue

**Answer (B):** make_widget() undergoes temporary materialization conversion ([conv.rval]) to an xvalue, and Widget::operator=(Widget&&) (or const Widget&) is called

**Why:** Mandatory prvalue elision applies only to initialization of a new object, never assignment to an existing object. Because operator= takes a reference parameter, temporary materialization ([conv.rval]) creates a temporary xvalue bound to operator='s parameter.
