# Reference binding and temporaries

> Which expressions bind to T&, const T&, and T&&, when implicit conversions silently materialize fresh temporaries, why lifetime extension stops at function boundaries, and C++23 range-for fixes.

- **Source:** C++ Atlas (https://cppatlas.com/topics/reference-binding-and-temporaries)
- **Track:** Value semantics
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [dcl.init.ref] (https://eel.is/c++draft/dcl.init.ref), [class.temporary] (https://eel.is/c++draft/class.temporary), [stmt.ranged] (https://eel.is/c++draft/stmt.ranged), [dcl.ref] (https://eel.is/c++draft/dcl.ref), [meta.unary.prop] (https://eel.is/c++draft/meta.unary.prop)
- **cppreference links:** [Reference initialization](https://en.cppreference.com/w/cpp/language/reference_initialization), [Reference declaration](https://en.cppreference.com/w/cpp/language/reference), [Lifetime](https://en.cppreference.com/w/cpp/language/lifetime), [Range-based for loop](https://en.cppreference.com/w/cpp/language/range-for), [Implicit conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion), [std::reference_constructs_from_temporary](https://en.cppreference.com/w/cpp/types/reference_constructs_from_temporary), [std::reference_converts_from_temporary](https://en.cppreference.com/w/cpp/types/reference_converts_from_temporary)
- **Prerequisites:** value-categories, casts-and-qualifiers

References look like simple aliases, yet two rules make them a prime source of silent dangling bugs: references can trigger implicit conversions that materialize unexpected temporary objects, and lifetime extension stops abruptly across function calls and constructors. Knowing exactly when a reference aliases an existing object versus when it anchors a freshly created temporary prevents subtle use-after-free bugs.

## The reference-binding matrix

C++ offers four reference types with strict rules over which value categories and cv-qualifications they accept (`[dcl.init.ref]`). Note that `const T&&` exists in the grammar, though almost its only practical use is writing `= delete` overloads (such as `std::as_const(const T&&) = delete;`) to reject rvalues cleanly.

| Reference parameter | Mutable `lvalue` (`T`) | `const lvalue` (`const T`) | Mutable `xvalue` / `prvalue` (`T`) | `const xvalue` / `prvalue` (`const T`) |
| --- | --- | --- | --- | --- |
| `T&` | Binds directly | Rejected | Rejected | Rejected |
| `const T&` | Binds directly | Binds directly | Binds (materializes prvalue) | Binds (materializes prvalue) |
| `T&&` | Rejected | Rejected | Binds (materializes prvalue) | Rejected |
| `const T&&` | Rejected | Rejected | Binds (materializes prvalue) | Binds (materializes prvalue) |

Two rules stand out immediately:

1. Non-const `T&` refuses rvalues because mutating an expiring temporary through a caller's output parameter is almost always a bug.
2. `const T&` binds every value category—and goes even further by invoking implicit conversions when types do not match directly.

> **Mental model.** A reference does not necessarily alias the exact expression you wrote; when types differ or a prvalue appears, `const T&` and `T&&` may silently materialize a brand-new temporary object just for the reference to hold onto.

## Silent temporaries during implicit conversion

Because `const T&` accepts convertible expressions of a different type, writing `double ratio = 3.75; const int& r = ratio;` compiles cleanly—and creates a **brand-new `int{3}` temporary** on the stack rather than aliasing `ratio`. Updating `ratio = 9.5;` leaves `r` equal to `3`! The exact same temporary materialization happens when passing `"hello"` to a function expecting `const std::string&`: a temporary `std::string` allocates, copies `"hello"`, binds to the parameter, and destroys when the full-expression ends.

> **Pitfall.** Binding `const T&` to a different or convertible type creates a hidden temporary object rather than aliasing the original variable—and silently dangles if stored in a reference member or returned from a function.

C++23 introduced `<type_traits>` predicates `std::reference_constructs_from_temporary_v<T, U>` and `std::reference_converts_from_temporary_v<T, U>` (`[meta.unary.prop]`) so generic containers like `std::tuple` and `std::pair` can detect and reject dangling bindings at compile time. Note carefully that passing a non-reference `U` (such as `std::string`) checks binding from a `U` **prvalue** (which does materialize a temporary), whereas `std::string&` checks an lvalue:

```cpp
#include <string>
#include <type_traits>

static_assert(std::reference_converts_from_temporary_v<const int&, double>);
static_assert(std::reference_converts_from_temporary_v<const std::string&, const char*>);
static_assert(std::reference_converts_from_temporary_v<const std::string&, std::string>);
static_assert(!std::reference_converts_from_temporary_v<const std::string&, std::string&>);

void implicit_temp_proof() {
    double d = 3.75;
    const int& r = d; // Binds to a temporary int{3}, NOT to d
    d = 9.5;          // r still reads 3!
    (void)r;
}
```

## Temporary lifetime and direct lifetime extension

Under `[class.temporary]`, temporary objects materialized during a full-expression are destroyed as the last step of evaluating that full-expression (typically at the semicolon), in strict reverse order of their creation.

A single narrow rule alters that schedule: **direct lifetime extension** (`[class.temporary]`). When a temporary is bound **directly** to a local reference variable (`const T&` or `T&&`), that temporary's lifetime extends to match the lifetime of the reference itself—including when binding to a direct non-static data member subobject (`const int& id = make_pair().first;`) or initializing a reference field of an aggregate (`struct View { const std::string& s; }; View v{"hi"};`). Notice that in `const int& id = make_pair().first;`, the **entire** `std::pair` temporary stays alive until `id` leaves scope, not only `.first`.

> **Standardese.** Under `[class.temporary]`, when a reference binds directly to a temporary prvalue or a member subobject thereof, that temporary's lifetime expands to match the reference's scope—except across specific syntactic boundaries listed by the standard.

## Five boundaries where lifetime extension stops

Lifetime extension is shallow and purely syntactic. The moment indirection enters, the temporary resumes dying at the full-expression's semicolon:

1. **Passing through a function returning a reference**: In `const T& r = identity(make_t());` (where `identity` returns `const T&`), the compiler cannot track provenance across function bodies, so `make_t()` dies at the semicolon and `r` dangles immediately.
2. **Member accessors and views (`make_vec().front()` or `std::string_view(make_str())`)**: Because `.front()` and `std::string_view` conversion are function calls rather than direct member subobject accesses, the owning `vector` or `string` dies at the semicolon while `r` or the view still points into freed storage.
3. **Constructor member initializers**: Binding a temporary to a reference member inside a constructor initializer list (`Holder(const T& t) : ref(t) {}` or `Holder() : ref(T{}) {}`) never extends the temporary beyond the constructor's full-expression.
4. **`return` statements**: Binding a local reference inside a `return` statement (`const T& x = make_t(); return x;`) destroys the temporary when the function stack frame unwinds.
5. **`new` expressions**: Temporaries bound within a `new` initializer do not outlive the full-expression containing `new`.

```cpp
#include <string>
#include <vector>

struct Wrapper {
    std::vector<int> items{10, 20, 30};
    const std::vector<int>& get_items() const { return items; }
};

Wrapper make_wrapper() { return Wrapper{}; }

void boundary_demo() {
    // Extended: direct binding to data member subobject of temporary Wrapper
    const std::vector<int>& safe = make_wrapper().items;

    // DANGLES immediately at semicolon: get_items() is a function call!
    // const std::vector<int>& bad = make_wrapper().get_items();
    (void)safe;
}
```

## Range-based for loops and C++23 P2718

For over a decade, range-based `for` loops suffered from one of C++'s sharpest traps. Because `for (auto x : range_expr)` expands roughly to `auto&& __range = range_expr;`, any outer temporary behind a chained accessor died at the semicolon **before the first loop iteration ever executed**:

```cpp
#include <vector>

struct RangeBox {
    std::vector<int> items{1, 2, 3};
    const std::vector<int>& get_items() const { return items; }
};

RangeBox make_box() { return RangeBox{}; }

// Pre-C++23: UB! RangeBox temporary died before the loop body started!
// C++23 (P2718R0): Well-defined! All range-initializer temporaries live across the loop.
void iterate_temporaries() {
    for (int v : make_box().get_items()) {
        (void)v;
    }
}
```

In C++11 through C++20, `make_box().get_items()` extended nothing because `__range` bound to the `const std::vector<int>&` returned by `get_items()`, leaving the outer `RangeBox` temporary to destruct immediately. C++23 paper **P2718R0** (`[stmt.ranged]`) changed the specification so that **all temporaries created inside the range-initializer expression** remain alive until the entire range-based `for` loop completes (and are destroyed in reverse order after the loop exits). Until your whole toolchain targets C++23 or newer, binding `auto box = make_box();` into a named variable before the loop remains the safest portable habit.

## What to remember

- `T&` binds only mutable lvalues, `T&&` binds only mutable rvalues, and `const T&` binds everything—including convertible types that materialize hidden temporaries.
- Direct reference binding extends a temporary (or whole object containing a bound data member or aggregate reference field) to the reference's scope.
- Lifetime extension stops cold at function calls (`std::string_view`, `.front()`, `identity()`), constructor initializer lists, `return` statements, and `new` expressions.
- C++23 (P2718R0) extends all temporaries in a range-based `for` initializer across the entire loop, fixing the classic `for (x : make().get_items())` dangling bug.

## Concept Map Outline

- **References and temporaries:** Reference initialization governs what expressions bind, when temporaries materialize, and how long they survive.
  - **Reference binding rules:** Four reference signatures accept distinct combinations of lvalues, rvalues, and constness.
    - **Non-const lvalue T&:** Binds exclusively to non-const lvalues and rejects temporaries or const objects.
    - **Rvalue reference T&&:** Binds exclusively to non-const xvalues and prvalues to enable resource stealing.
    - **Universal const T&:** Binds to lvalues, rvalues, and implicitly convertible expressions of different types.
  - **Implicit conversion temporaries:** Binding const T& across incompatible types materializes a fresh unrelated temporary object.
    - **Type mismatch copy:** Binding const int& to a double creates a separate int temporary unaffected by later writes.
    - **C++23 detection traits:** reference_constructs_from_temporary and reference_converts_from_temporary catch dangling binds.
  - **Direct lifetime extension:** Binding a local reference directly to a temporary extends its lifetime to that scope.
    - **Full-expression baseline:** Unextended temporaries destruct at the end of the enclosing full-expression in reverse order.
    - **Subobject and aggregate:** Binding a temporary's data member or aggregate reference field extends the whole temporary.
  - **Where extension stops:** Syntactic indirection through calls or constructors cancels temporary lifetime extension.
    - **Function call return:** Passing a temporary through an identity function or accessor lets it die at the semicolon.
    - **Constructor member init:** Binding a temporary to a reference member inside a constructor always dangles after construction.
    - **Return and new expressions:** Temporaries bound inside return statements or new expressions never extend past their context.
  - **Range-for and P2718R0:** C++23 closes the classic chained-temporary dangling loophole inside range-based for loops.
    - **Pre-C++23 __range cliff:** Chaining a member accessor in C++11 through C++20 left the outer temporary dead before iteration.
    - **C++23 loop-wide lifetime:** P2718R0 extends every temporary in the range-initializer expression until the loop ends.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init.ref])

Which reference parameter type refuses to bind to `const Widget cw;` while accepting `Widget{}`?

A. const Widget&
B. Widget&&
C. const Widget&&
D. Widget&

**Answer (B):** Widget&&

**Why:** Widget&& binds only non-const rvalues (xvalues and prvalues like Widget{}), rejecting lvalues such as cw. const Widget& and const Widget&& accept const rvalues (though const Widget& also accepts cw), while Widget& rejects both.

### Question 2 [warmup] ([dcl.init.ref], [class.temporary])

What value does `r` observe after `d = 9.5;` runs in this snippet?

```cpp
double d = 3.75;
const int& r = d;
d = 9.5;
```

A. 3, because r bound to a temporary int{3} created by converting d rather than aliasing d
B. 9, because r aliases d and truncates its updated value on read
C. Compilation error: const int& cannot bind to a double
D. Undefined behavior due to strict aliasing between int and double

**Answer (A):** 3, because r bound to a temporary int{3} created by converting d rather than aliasing d

**Why:** Because int and double are not reference-related, binding const int& to double d implicitly converts d into a fresh temporary int{3} whose lifetime is extended to r. Subsequent writes to d never affect that hidden temporary.

### Question 3 [tricky] ([class.temporary])

In which snippet does `r` (or `h.ref`) remain valid rather than dangling immediately after the semicolon?

```cpp
struct Pair { int first; int second; };
Pair make_pair() { return {1, 2}; }
const int& id(const int& x) { return x; }
struct Holder {
    const int& ref;
    Holder(const int& x) : ref(x) {}
};
```

A. const int& r = id(10);
B. Holder h(10);
C. const int& r = make_pair().first;
D. std::string_view sv = std::string("abc");

**Answer (C):** const int& r = make_pair().first;

**Why:** Binding a reference directly to a non-static data member subobject of a temporary (make_pair().first) extends the entire temporary Pair object's lifetime to r. Passing through id(), storing via a non-aggregate constructor Holder, or constructing std::string_view stops lifetime extension.

### Question 4 [tricky] ([stmt.ranged], [class.temporary])

In C++17 and C++20 (before C++23 P2718R0), what happens in `for (int x : make_box().get_vec())` when `get_vec()` returns `const std::vector<int>&`?

```cpp
struct Box {
    std::vector<int> vec{1, 2, 3};
    const std::vector<int>& get_vec() const { return vec; }
};
Box make_box();
```

A. Well-defined in all C++ versions because range-for extends every temporary in the header
B. Well-defined only if int x is changed to const auto& x
C. Compile error in C++17/C++20
D. Undefined behavior in C++17/C++20 because auto&& __range binds to get_vec()'s return reference, letting the Box temporary destruct before the loop starts

**Answer (D):** Undefined behavior in C++17/C++20 because auto&& __range binds to get_vec()'s return reference, letting the Box temporary destruct before the loop starts

**Why:** In C++11 through C++20, range-for initializes auto&& __range = make_box().get_vec();. Because get_vec() is a member function call, __range does not extend the Box temporary, which is destroyed at the semicolon before iteration begins. C++23 P2718R0 fixed this in [stmt.ranged].

### Question 5 [standardese] ([meta.unary.prop], [dcl.init.ref])

What do `std::reference_converts_from_temporary_v<const std::string&, std::string>` and `std::reference_converts_from_temporary_v<const std::string&, std::string&>` evaluate to in C++23?

A. false and false, because both have the same underlying type std::string
B. true and false, because std::string (unqualified) models a prvalue that materializes a temporary, whereas std::string& is an lvalue that binds directly
C. false and true
D. true and true

**Answer (B):** true and false, because std::string (unqualified) models a prvalue that materializes a temporary, whereas std::string& is an lvalue that binds directly

**Why:** In <type_traits> ([meta.unary.prop]), the second template argument U models an expression of type declval<U>(). When U is std::string (non-reference), declval<std::string>() is an rvalue, so binding const std::string& creates/materializes a temporary (true). When U is std::string&, declval<std::string&>() is an lvalue and binds directly (false).

### Question 6 [standardese] ([class.temporary])

When an aggregate struct `struct Agg { const std::string& s; };` is aggregate-initialized via `Agg a{"hello"};`, what is the lifetime of the materialized `std::string` temporary?

```cpp
struct Agg { const std::string& s; };
Agg a{"hello"};
```

A. It is destroyed at the semicolon of Agg a{"hello"};, leaving a.s dangling
B. It is extended to match the lifetime of a (the enclosing aggregate object)
C. It lives in static storage until program exit
D. Aggregate initialization of a reference member from a string literal is ill-formed

**Answer (B):** It is extended to match the lifetime of a (the enclosing aggregate object)

**Why:** Under [class.temporary]/6.1, a temporary bound to a reference element of an aggregate via aggregate initialization has its lifetime extended to match the lifetime of the aggregate object a itself—unlike a user-declared constructor's mem-initializer, which does not extend lifetime.
