# Copy elision

> C++ Atlas: `cppatlas.com/w/cpp/language/copy_elision` | Source: https://en.cppreference.com/w/cpp/language/copy_elision | Domain: Language | Standards: C++11, C++14, C++17, C++20, C++23

When certain criteria are met, the creation of a class object from a source object of the same type (ignoring cv-qualification) can be omitted, even if the selected constructor and/or the destructor for the object have side effects.

## Executive Mental Model (Study Companion)

**Core Intuition:** A prvalue in C++17+ is not an object in memory—it is an unmaterialized recipe to initialize a target slot.

- **Standard Era:** C++11 → C++17 → C++23
- **Primary ISO Clauses:** [basic.lval], [conv.rval], [class.copy.elision], [dcl.type.decltype]
- **CppCon Talk Angle:** Show how C++17 reversed the arrow: previously prvalues were temporary objects we tried to elide away; now prvalues only become objects when materialization is forced.
- **Common Audience Trap:** Conflating an identifier's declared type (Widget&&) with its expression value category (lvalue inside the function body).
- **Stage Takeaway:** Never write return std::move(local); — it turns an implicit move-eligible lvalue into an explicit xvalue that blocks NRVO.

## Memory Map Walkthrough: C++17 Value Category Taxonomy & Materialization

C++17 classifies every expression along two orthogonal axes: glvalue (has identity, you can take its address or distinguish it from another object) and rvalue (eligible to be moved from). An lvalue has identity and cannot be moved from implicitly; a prvalue has no identity yet because it is an unmaterialized initialization recipe; an xvalue sits at the intersection of both—an expiring object that already occupies memory and can have its resources pilfered. Temporary materialization conversion converts a prvalue into an xvalue only at the exact boundary where an object identity is required, such as binding a reference or accessing a member.

### Identity vs. movability ([basic.lval] §7.2.1)

Forget 'left side vs right side of an assignment'. In modern C++, an expression is classified by two orthogonal questions: Does evaluation determine the identity of an existing object or function (glvalue)? And may its resources be reused because nothing else observes it afterward (rvalue)?

An lvalue has identity but is not movable. A prvalue ('pure rvalue') is an unmaterialized computation or initializer with no address of its own. An xvalue ('eXpiring value') is the overlap: an object that already exists in memory whose lifetime is about to end or was explicitly cast via std::move.

*Type vs. value category orthogonality:*
```cpp
void consume(Widget& w);   // binds lvalues
void consume(Widget&& w);  // binds rvalues (xvalue or prvalue)

void relay(Widget&& param) {
    // 'param' has type Widget&&, yet the expression 'param' is an LVALUE
    // because it has a name and an addressable location.
    consume(param);            // calls consume(Widget&)
    consume(std::move(param)); // xvalue -> calls consume(Widget&&)
}
```

**Key takeaway:** Named rvalue references are always lvalues inside expressions; only unnamed rvalue references (like std::move's return value) are xvalues.

### C++17 deferred temporary materialization ([conv.rval] & [class.copy.elision])

Prior to C++17, Widget w = Widget(42); conceptually created a temporary Widget, called the move constructor into w, and then allowed the compiler to elide that move—which still forced Widget's move constructor to be accessible.

C++17 fixed this at the grammar level. Widget(42) is a prvalue initialization recipe passed down to w's storage slot. No temporary object exists unless something forces temporary materialization ([conv.rval]), such as binding to const Widget& or reading .field on a temporary.

*Non-copyable, non-movable type returned by value:*
```cpp
struct Locked {
    int token;
    explicit Locked(int t) : token(t) {}
    Locked(const Locked&) = delete;
    Locked(Locked&&) = delete;
};

Locked make_locked() {
    return Locked{99}; // Legal since C++17: initializes caller slot directly
}

Locked x = make_locked(); // Zero moves, zero copies required
```

**Key takeaway:** Prvalue chains (make() -> make() -> variable) collapse into a single in-place construction at the final destination.

## Official Specification Summary (cppreference)

When certain criteria are met, the creation of a class object from a source object of the same type (ignoring cv-qualification) can be omitted, even if the selected constructor and/or the destructor for the object have side effects. This elision of object creation is called *copy elision*.

### Explanation

Copy elision is permitted in the following circumstances (which may be combined to eliminate multiple copies):

- In a `return` statement in a function with a class return type, when the operand is the name of a non-volatile object `obj` with automatic storage duration (other than a function parameter or a handler parameter), the copy-initialization of the result object can be omitted by constructing `obj` directly into the function call’s result object. This variant of copy elision is known as *named return value optimization* (NRVO).

(until C++17):

- When a class object `target` is copy-initialized with a temporary class object `obj` that has not been bound to a reference, the copy-initialization can be omitted by constructing `obj` directly into `target`. This variant of copy elision is known as *unnamed return value optimization* (URVO). Since C++17, URVO is mandatory and no longer considered a form of copy elision; see below.

(since C++11):

- In a `throw` expression, when the operand is the name of a non-volatile object `obj` with automatic storage duration (other than a function parameter or a handler parameter) that belongs to a scope that does not contain the innermost enclosing `try` block (if exists), the copy-initialization of the exception object can be omitted by constructing `obj` directly into the exception object.
- In a handler, the copy-initialization of the handler argument can be omitted by treating the handler parameter as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the handler argument.

(since C++20):

- In coroutines, a copy of a coroutine parameter can be omitted. In this case, references to that copy are replaced with references to the corresponding parameter if the meaning of the program will be unchanged except for the execution of a constructor and destructor for the parameter copy object.

When copy elision occurs, the implementation treats the source and target of the omitted initialization as simply two different ways of referring to the same object.

The destruction occurs at the later of the times when the two objects would have been destroyed without the optimization. (until C++11)

If the first parameter of the selected constructor is an rvalue reference to the object’s type, the destruction of that object occurs when the target would have been destroyed. Otherwise, the destruction occurs at the later of the times when the two objects would have been destroyed without the optimization. (since C++11)

(since C++17):

### Prvalue semantics ("guaranteed copy elision")

Since C++17, a prvalue is not materialized until needed, and then it is constructed directly into the storage of its final destination. This sometimes means that even when the language syntax visually suggests a copy/move (e.g. copy initialization), no copy/move is performed — which means the type need not have an accessible copy/move constructor at all. Examples include:

- Initializing the returned object in a return statement, when the operand is a prvalue of the same class type (ignoring cv-qualification) as the function return type:

```cpp
T f()
{
    return U(); // constructs a temporary of type U,
                // then initializes the returned T from the temporary
}
T g()
{
    return T(); // constructs the returned T directly; no move
}
```

  The destructor of the type returned must be accessible at the point of the return statement and non-deleted, even though no T object is destroyed.

- In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:

```cpp
T x = T(T(f())); // x is initialized by the result of f() directly; no move
```

  This can only apply when the object being initialized is known not to be a potentially-overlapping subobject:

```cpp
struct C { /* ... */ };
C f();

struct D;
D g();

struct D : C
{
    D() : C(f()) {}    // no elision when initializing a base class subobject
    D(int) : D(g()) {} // no elision because the D object being initialized might
                       // be a base-class subobject of some other class
};
```

Note: This rule does not specify an optimization, and the Standard does not formally describe it as "copy elision" (because nothing is being elided). Instead, the C++17 core language specification of prvalues and temporaries is fundamentally different from that of earlier C++ revisions: there is no longer a temporary to copy/move from. Another way to describe C++17 mechanics is "unmaterialized value passing" or "deferred temporary materialization": prvalues are returned and used without ever materializing a temporary.

### Notes

Copy elision is the only allowed form of optimization (until C++14) one of the two allowed forms of optimization, alongside allocation elision and extension, (since C++14) that can change observable side-effects. Because some compilers do not perform copy elision in every situation where it is allowed (e.g., in debug mode), programs that rely on the side-effects of copy/move constructors and destructors are not portable.

(since C++11):

In a `return` statement or a `throw` expression, if the compiler cannot perform copy elision but the conditions for copy elision are met, or would be met except that the source is a function parameter, the compiler will attempt to use the move constructor even if the source operand is designated by an lvalue (until C++23) the source operand will be treated as an rvalue (since C++23); see `return` statement for details.

In constant expression and constant initialization, copy elision is never performed.

```cpp
struct A
{
    void* p;
    constexpr A() : p(this) {}
    A(const A&); // Disable trivial copyability
};

constexpr A a;  // OK: a.p points to a

constexpr A f()
{
    A x;
    return x;
}
constexpr A b = f(); // error: b.p would be dangling and point to the x inside f

constexpr A c = A(); // (until C++17) error: c.p would be dangling and point to a temporary
                     // (since C++17) OK: c.p points to c; no temporary is involved
```

| Feature-test macro | Value | Std | Feature |
| --- | --- | --- | --- |
| `__cpp_guaranteed_copy_elision` | `201606L` | (C++17) | Guaranteed copy elision through simplified value categories |

### Example

```cpp
#include <iostream>

struct Noisy
{
    Noisy() { std::cout << "constructed at " << this << '\n'; }
    Noisy(const Noisy&) { std::cout << "copy-constructed\n"; }
    Noisy(Noisy&&) { std::cout << "move-constructed\n"; }
    ~Noisy() { std::cout << "destructed at " << this << '\n'; }
};

Noisy f()
{
    Noisy v = Noisy(); // (until C++17) copy elision initializing v from a temporary;
                       //               the move constructor may be called
                       // (since C++17) "guaranteed copy elision"
    return v; // copy elision ("NRVO") from v to the result object;
              // the move constructor may be called
}

void g(Noisy arg)
{
    std::cout << "&arg = " << &arg << '\n';
}

int main()
{
    Noisy v = f(); // (until C++17) copy elision initializing v from the result of f()
                   // (since C++17) "guaranteed copy elision"

    std::cout << "&v = " << &v << '\n';

    g(f()); // (until C++17) copy elision initializing arg from the result of f()
            // (since C++17) "guaranteed copy elision"
}
```

Possible output:

```text
constructed at 0x7fffd635fd4e
&v = 0x7fffd635fd4e
constructed at 0x7fffd635fd4f
&arg = 0x7fffd635fd4f
destructed at 0x7fffd635fd4f
destructed at 0x7fffd635fd4e
```

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| CWG 1967 | C++11 | when copy elision is done using a move constructor, the lifetime of the moved-from object was still considered | not considered |
| CWG 2426 | C++17 | destructor was not required when returning a prvalue | destructor is potentially invoked |
| CWG 2930 | C++98 | only copy(/move) operations could be elided, but a non-copy(/move) constructor can be selected by copy-initialization | elides any object construction of related copy-initializations |

### See also

- [copy initialization](https://en.cppreference.com/w/cpp/language/copy_initialization)
- [copy constructor](https://en.cppreference.com/w/cpp/language/copy_constructor)
- [move constructor](https://en.cppreference.com/w/cpp/language/move_constructor)

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Debate why teaching 'lvalue means left-hand side of =' actively breaks programmers once const variables and std::move enter the picture.
- Walk through how C++17 deferred materialization makes non-movable types like std::atomic<int> returnable by value.
- Quiz each other on why "hello" is an lvalue and why return std::move(local) is a classic performance pessimization.

### Trap 1: [lex.string] §5.13.5 (standard-lawyer)

What is the value category and exact type of the string literal expression "cppcon"?

```cpp
auto p = &"cppcon";
```

A. prvalue of type const char*
B. lvalue of type const char[7]
C. prvalue of type const char[7]
D. xvalue of type const char(&)[7]

**Standard Answer (B):** lvalue of type const char[7]

**Why:** Unlike numeric literals such as 42 (which are prvalues), string literals have static storage duration in read-only memory. They are lvalues of array type const char[N] including the null terminator, which is why taking &"cppcon" compiles cleanly.

*CppCon speaker note:* Great opening warm-up slide at CppCon: 80% of the room picks prvalue by analogy with integer literals.

### Trap 2: [dcl.type.decltype] §9.2.9.6 (subtle)

Given int x = 10;, what are the deduced types of a and b below?

```cpp
int x = 10;
decltype(x)   a = x;
decltype((x)) b = x;
```

A. a is int, b is int
B. a is int&, b is int&
C. a is int, b is int&
D. a is int, b is int&&

**Standard Answer (C):** a is int, b is int&

**Why:** decltype has two rules: on an unparenthesized id-expression (x), it yields the declared type (int). Wrapping parentheses turns (x) into a general expression, where decltype yields T& for lvalues, T&& for xvalues, and T for prvalues.

### Trap 3: [class.copy.elision] §11.9.6 (cppcon-stage)

In C++17 and later, what happens when returning a named local variable via return std::move(buf);?

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

A. Faster than return buf; because it forces a move instead of a copy
B. Prevents NRVO and forces a move construction instead of zero-cost in-place construction
C. Undefined behavior because buf is destroyed before the move finishes
D. Triggers guaranteed C++17 copy elision

**Standard Answer (B):** Prevents NRVO and forces a move construction instead of zero-cost in-place construction

**Why:** NRVO (Named Return Value Optimization) only applies when the return operand is the plain name of an automatic local variable. Wrapping it in std::move(buf) changes the expression to a function call yielding an xvalue, blocking NRVO and forcing an actual move constructor call (-Wpessimizing-move).

*CppCon speaker note:* Emphasize: plain return buf; already moves implicitly if NRVO doesn't happen, so std::move here can only hurt.

### Trap 4: [expr.ref] §7.6.1.5 (standard-lawyer)

Given struct S { int m; }; and a function S make_s();, what is the value category of make_s().m?

```cpp
struct S { int m; };
S make_s();
// What is make_s().m ?
```

A. lvalue
B. prvalue
C. xvalue
D. Ill-formed because make_s() is unmaterialized

**Standard Answer (C):** xvalue

**Why:** Member access E1.E2 on a prvalue E1 first triggers temporary materialization ([conv.rval]), turning make_s() into a temporary xvalue. A non-static data member access on an rvalue yields an xvalue designating that subobject.

### Trap 5: [expr.pre.incr] & [expr.post.incr] (subtle)

For built-in int i = 0;, which expression is well-formed C++?

```cpp
int i = 0;
```

A. &(i++)
B. (i++) = 5
C. ++ ++i
D. int& r = i++;

**Standard Answer (C):** ++ ++i

**Why:** Built-in prefix ++i modifies i and yields an lvalue referring to i, so chaining ++ ++i mutates i twice validly. Built-in postfix i++ produces a prvalue copy of the old value, which cannot have its address taken, be assigned to, or bind to a non-const lvalue ref.

---
Attribution: content from https://en.cppreference.com/w/cpp/language/copy_elision (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.