# Reference initialization

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

Binds a reference to an object.

## Executive Mental Model (Study Companion)

**Core Intuition:** Allocating bytes does not create an object, and freeing bytes is not what destroys one—lifetime begins at initialization and ends at destruction or storage reuse.

- **Standard Era:** C++11 → C++17 → C++20 → C++23
- **Primary ISO Clauses:** [basic.life], [basic.stc], [class.temporary], [stmt.ranged]
- **CppCon Talk Angle:** Show the two timelines side by side: storage duration (how long the bytes exist) vs. object lifetime (when the typed object is legally alive inside those bytes).
- **Common Audience Trap:** Assuming temporary lifetime extension propagates through accessor methods like auto& x = make_container().front(); inside range-for loops.
- **Stage Takeaway:** Use C++20 std::bit_cast instead of pointer-punning reinterpret_cast, and verify C++23 P2718 before trusting chained temporaries in range-for.

## Memory Map Walkthrough: Virtual Address Space & Scope Lifetime Scrubber

In C++, storage duration and object lifetime are distinct concepts. Storage duration governs when raw memory exists—static, thread-local, automatic on the stack, or dynamic on the heap—while object lifetime begins only when initialization completes and ends when the destructor starts or the storage is reused. Binding a temporary directly to a const lvalue reference or rvalue reference extends its lifetime to the reference's scope, but chaining through a member function or accessor stops lifetime extension cold, creating a classic dangling reference before C++23's range-for fix (P2718R0). Meanwhile, placement-new reusing storage that contained const or reference subobjects requires std::launder so the optimizer does not reuse cached values from the previous object.

### Storage duration is not object lifetime ([basic.life] §6.7.3)

When you allocate raw aligned storage (alignas(Widget) std::byte buf[sizeof(Widget)];), storage exists, yet zero Widget objects live there. Accessing a Widget* pointing to buf before placement-new construction is Undefined Behavior.

C++20 softened one long-standing C interop pain point with Implicit-Lifetime Types ([intro.object]): malloc or std::start_lifetime_as (C++23) can implicitly begin the lifetime of trivial aggregates/arrays so C network buffers no longer rely on theoretical UB.

*Why std::launder exists for const members:*
```cpp
struct Node { const int id; };
Node* p = new Node{1};
// Reuse p's storage with placement new:
new (p) Node{2};
// Compiler may legally assume p->id is STILL 1 because 'id' is const!
int safe_id = std::launder(p)->id; // Guaranteed 2 ([ptr.launder])
```

**Key takeaway:** Compilers track pointer provenance and const member immutability; std::launder tells the optimizer a fresh object replaced the old one at that address.

### Temporary lifetime extension & the range-for cliff ([class.temporary] & [stmt.ranged])

Writing const std::string& s = make_name(); extends the materialized temporary string to match s's scope. Write const char* p = make_name().c_str(); or auto& item : get_wrapper().items() in C++11–C++20, and the outer temporary wrapper is destroyed BEFORE the loop body even begins!

C++23 paper P2718R0 finally fixed range-based for loops by extending the lifetime of ALL temporaries in the range-initializer expression until the loop finishes—matching what every developer already assumed.

*Pre-C++23 range-for dangling temporary:*
```cpp
struct Wrapper { std::vector<int> items{1, 2, 3}; };
Wrapper make_wrapper();

// Pre-C++23: UB! Wrapper temporary dies before loop starts!
// C++23 (P2718R0): Well-defined! All temporaries in range-init extend across loop.
for (int v : make_wrapper().items) {
    use(v);
}
```

**Key takeaway:** Whenever a function returns a reference or view into a temporary receiver (std::string_view, std::span, or .items), check whether you are pre-C++23.

## Official Specification Summary (cppreference)

Binds a reference to an object.

### Syntax

##### Non-list-initialization

- *T* `&` *ref* `=` *target* `;` *T* `&` *ref* `(` *target* `);`    (1)
- *T* `&&` *ref* `=` *target* `;` *T* `&&` *ref* `(` *target* `);`    (2) (since C++11)
- *func-refpar* `(` *target* `)`    (3)
- `return` *target* `;`    (4) (inside the definition of func-refret )
- *Class*`::`*Class*`(`...`):` *ref-member* `(` *target* `) {`... `}`    (5) (inside the definition of Class )

##### Ordinary list-initialization (since C++11)

- *T* `&` *ref* `= {` *arg1*`,` *arg2*`,`... `};` *T* `&` *ref* `{` *arg1*`,` *arg2*`,`... `};`    (1)
- *T* `&&` *ref* `= {` *arg1*`,` *arg2*`,`... `};` *T* `&&` *ref* `{` *arg1*`,` *arg2*`,`... `};`    (2)
- *func-refpar* `({` *arg1*`,` *arg2*`,`... `});`    (3)

##### Designated list-initialization (since C++20)

- *T* `&` *ref* `= {.`*des1* `=` *arg1* `,.`*des2* `{` *arg2* `}`... `};` *T* `&` *ref* `{.`*des1* `=` *arg1* `,.`*des2* `{` *arg2* `}`... `};`    (1)
- *T* `&&` *ref* `= {.`*des1* `=` *arg1* `,.`*des2* `{` *arg2* `}`... `};` *T* `&&` *ref* `{.`*des1* `=` *arg1* `,.`*des2* `{` *arg2* `}`... `};`    (2)
- *func-refpar* `({.`*des1* `=` *arg1* `,.`*des2* `{` *arg2* `}`... `});`    (3)

A reference to `T` can be initialized with an object of type `T`, a function of type `T`, or an object implicitly convertible to `T`. Once initialized, a reference cannot be reseated (changed) to refer to another object.

References are initialized in the following situations:

1) When a named lvalue reference variable is declared with an initializer.

2) When a named rvalue reference variable is declared with an initializer.

3) In a function call expression, when the function parameter has reference type.

4) In the `return` statement, when the function returns a reference type. The program is ill-formed if the returned reference is bound to the result of a temporary expression. (since C++26)

5) When a non-static data member of reference type is initialized using a member initializer.

### Explanation

- `T` - the referenced type
- `ref` - the reference variable to be initialized
- `target` - the initializer expression being used
- `func-refpar` - a function with a parameter of reference type (*T* `&` or *T* `&&` (since C++11))
- `func-refret` - a function whose returns type is a reference type (*T* `&` or *T* `&&` (since C++11))
- `Class` - a class name
- `ref-member` - a non-static data member of reference type (*T* `&` or *T* `&&` (since C++11)) of *Class*
- `des1, des2, ...` - designators
- `arg1, arg2, ...` - the initializers in initializer lists

### Definitions

For two types `T1` and `T2`:

- Given the cv-unqualified versions of `T1` and `T2` as `U1` and `U2` respectively, if `U1` is similar to `U2`, or `U1` is a base class of `U2`, `T1` is *reference-related* to `T2`.
- If a prvalue of type “pointer to `T2`” can be converted to the type “pointer to `T1`” via a standard conversion sequence, `T1` is *reference-compatible* with `T2`.

### Initialization rules

If a reference initialization uses an ordinary or designated (since C++20) list-initialization, the rules of list-initialization are followed. (since C++11)

For non-list reference initialization, given the type of *target* as `U`, the reference either *binds directly* to *target* or binds to a value of type `T` converted from *target*. Direct binding is considered first, followed by indirect binding, if neither binding is available, the program is ill-formed.

In all cases where the reference-compatible relationship of two types is used to establish the validity of a reference binding and the standard conversion sequence would be ill-formed, a program that necessitates such a binding is ill-formed.

#### Direct binding

If all following conditions are satisfied:

- The reference to be initialized is an lvalue reference.
- *target* is a non-bit-field lvalue.
- `T` is reference-compatible with `U`.

Then the reference binds to *target*, or to its appropriate base class subobject:

```cpp
double d = 2.0;
double& rd = d;        // rd refers to d
const double& rcd = d; // rcd refers to d

struct A {};
struct B : A {} b;

A& ra = b;             // ra refers to A subobject in b
const A& rca = b;      // rca refers to A subobject in b
```

Otherwise, if all following conditions are satisfied:

- The reference to be initialized is an lvalue reference.
- `U` is a class type.
- `T` is not reference-related to `U`.
- *target* can be converted to an lvalue of type `V` such that `T` is reference-compatible with `V`.

Then the reference binds to the lvalue result of the conversion, or to its appropriate base class subobject:

```cpp
struct A {};
struct B : A { operator int&(); };

int& ir = B(); // ir refers to the result of B::operator int&
```

Otherwise, if the reference to be initialized is an lvalue reference, and `T` is not const-qualified or is volatile-qualified, the prorgram is ill-formed:

```cpp
double& rd2 = 2.0; // error: not an lvalue and reference is not const
int i = 2;
double& rd3 = i;   // error: type mismatch and reference is not const
```

Otherwise, if all following conditions are satisfied:

- *target* is a value of any following category:

  - rvalue (until C++11)

  - non-bit-field xvalue
  - class prvalue
  - array prvalue
  - function lvalue (since C++11) (until C++17)

  - non-bit-field rvalue
  - function lvalue (since C++17)

- `T` is reference-compatible with `U`.

Then the reference binds to *target*, or to its appropriate base class subobject:

```cpp
struct A {};
struct B : A {};
extern B f();

const A& rca2 = f(); // bound to the A subobject of the B rvalue.
A&& rra = f();       // same as above

int i2 = 42;
int&& rri = static_cast<int&&>(i2); // bound directly to i2
```

(since C++17):

If *target* is a prvalue, temporary materialization is applied to it, considering the type of the prvalue to be the adjusted type `P`.

- `P` is adjusted from the type of *target* (i.e. `U`) by adding the cv-qualification of `T` to it.

In this case, the reference binds to the result object, or to its appropriate base class subobject.

Otherwise, if all following conditions are satisfied:

- `U` is a class type.
- `T` is not reference-related to `U`.
- *target* can be converted to a value `v` of type `V` such that `T` is reference-compatible with `V`, where `v` is of any following category:

  - rvalue (until C++11)

  - xvalue
  - class prvalue
  - function lvalue (since C++11) (until C++17)

  - rvalue
  - function lvalue (since C++17)

Then the reference binds to the result of the conversion, or to its appropriate base class subobject:

```cpp
struct A {};
struct B : A {};
struct X { operator B(); } x;

const A& r = x; // bound to the A subobject of the result of the conversion
B&& rrb = x;    // bound directly to the result of the conversion
```

(since C++17):

If the result of the conversion is a prvalue, temporary materialization is applied to it, considering the type of the prvalue to be the adjusted type `P`.

- `P` is adjusted from the type of the conversion result by adding the cv-qualification of `T` to it.

In this case, the reference binds to the result object, or to its appropriate base class subobject.

#### Indirect binding

If direct binding is not available, indirect binding is considered. In this case, `T` cannot be reference-related to `U`.

If `T` or `U` is a class type, user-defined conversions are considered using the rules for copy-initialization of an object of type `T` by user-defined conversion. The program is ill-formed if the corresponding non-reference copy-initialization would be ill-formed. The result of the call to the conversion function, as described for the non-reference copy-initialization, is then used to direct-initialize the reference. For this direct-initialization, user-defined conversions are not considered.

Otherwise, a temporary of type `T` is created and copy-initialized from *target*. The reference is then bound to the temporary. (until C++17)

Otherwise, *target* is implicitly converted to a prvalue of type “cv-unqualified `T`”. The temporary materialization conversion is applied, considering the type of the prvalue to be `T`, and the reference is bound to the result object. (since C++17)

```cpp
const std::string& rs = "abc"; // rs refers to temporary copy-initialized from char array
const double& rcd2 = 2;        // rcd2 refers to temporary with value 2.0
int i3 = 2;
double&& rrd3 = i3;            // rrd3 refers to temporary with value 2.0
```

### Lifetime of a temporary

Whenever a reference is bound to a temporary object or to a subobject thereof, the lifetime of the temporary object is extended to match the lifetime of the reference (check temporary object lifetime exceptions), where the temporary object or its subobject is denoted by one of following expression:

(until C++17):

- a prvalue expression of an object type,

(since C++17):

- a temporary materialization conversion,

- a parenthesized expression `(e)`, where `e` is one of these expressions,
- a built-in subscript expression of form `a[n]` or `n[a]`, where `a` is an array and is one of these expressions,
- a class member access expression of form `e.m`, where `e` is one of these expressions and `m` designates a non-static data member of object type,
- a pointer-to-member operation of form `e.*mp`, where `e` is one of these expressions and `mp` is a pointer to data member,
- a `const_cast`, `static_cast`, `dynamic_cast`, or `reinterpret_cast` conversion without a user-defined conversion that converts one of these expressions to the glvalue refers to the object designated by the operand, or to its complete object or a subobject thereof (an explicit cast expression is interpreted as a sequence of these casts),
- a conditional expression of form `cond ? e1: e2` that is a glvalue, where `e1` or `e2` is one of these expressions, or
- a built-in comma expression of form `x, e` that is a glvalue, where `e` is one of these expressions.

There are following exceptions to this lifetime rule:

(until C++26):

- a temporary bound to a return value of a function in a `return` statement is not extended: it is destroyed immediately at the end of the return expression. Such `return` statement always returns a dangling reference.

- a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.

(since C++11):

- a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference.

(since C++20):

- a temporary bound to a reference in a reference element of an aggregate initialized using direct-initialization syntax **(**parentheses**)** exists until the end of the full expression containing the initializer, as opposed to list-initialization syntax **{**braces**}**.

```cpp
struct A
{
    int&& r;
};

A a1{7}; // OK, lifetime is extended
A a2(7); // well-formed, but dangling reference
```

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data member to which the temporary was bound, does not affect its lifetime.

### Notes

References appear without initializers only in function parameter declaration, in function return type declaration, in the declaration of a class member, and with the `extern` specifier.

Until the resolution of CWG issue 1696, a temporary is permitted to bound to a reference member in a constructor initializer list, and it persists only until the constructor exits, not as long as the object exists. Such initialization is ill-formed since CWG 1696, although many compilers still support it (a notable exception is clang).

### Example

```cpp
#include <sstream>
#include <utility>

struct S
{
    int mi;
    const std::pair<int, int>& mp; // reference member
};

void foo(int) {}

struct A {};

struct B : A
{
    int n;
    operator int&() { return n; }
};

B bar() { return B(); }

//int& bad_r;      // error: no initializer
extern int& ext_r; // OK

int main()
{
//  Lvalues
    int n = 1;
    int& r1 = n;                    // lvalue reference to the object n
    const int& cr(n);               // reference can be more cv-qualified
    volatile int& cv{n};            // any initializer syntax can be used
    int& r2 = r1;                   // another lvalue reference to the object n
//  int& bad = cr;                  // error: less cv-qualified
    int& r3 = const_cast<int&>(cr); // const_cast is needed

    void (&rf)(int) = foo; // lvalue reference to function
    int ar[3];
    int (&ra)[3] = ar;     // lvalue reference to array

    B b;
    A& base_ref = b;        // reference to base subobject
    int& converted_ref = b; // reference to the result of a conversion

//  Rvalues
//  int& bad = 1;        // error: cannot bind lvalue ref to rvalue
    const int& cref = 1; // bound to rvalue
    int&& rref = 1;      // bound to rvalue

    const A& cref2 = bar(); // reference to A subobject of B temporary
    A&& rref2 = bar();      // same

    int&& xref = static_cast<int&&>(n); // bind directly to n
//  int&& copy_ref = n;                 // error: can't bind to an lvalue
    double&& copy_ref = n;              // bind to an rvalue temporary with value 1.0

//  Restrictions on temporary lifetimes
//  std::ostream& buf_ref = std::ostringstream() << 'a';
                     // the ostringstream temporary was bound to the left operand
                     // of operator<< but its lifetime ended at the semicolon so
                     // the buf_ref is a dangling reference

    S a {1, {2, 3}}; // temporary pair {2, 3} bound to the reference member
                     // a.mp and its lifetime is extended to match
                     // the lifetime of object a

    S* p = new S{1, {2, 3}}; // temporary pair {2, 3} bound to the reference
                             // member p->mp, but its lifetime ended at the semicolon
                             // p->mp is a dangling reference
    delete p;

    // Imitate [[maybe_unused]] applied to the following variables:
    [](...){}
    (
        cv, r2, r3, rf, ra, base_ref, converted_ref,
        a, cref, rref, cref2, rref2, copy_ref, xref
    );
}
```

### 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 391 | C++98 | initialize a reference to const-qualified type with a class type rvalue might create a temporary, and a constructor of that class was required in order to copy the rvalue into that temporary | no temporary is created, constructor is not required |
| CWG 450 | C++98 | a reference to const-qualified array could not be initialized with a reference-compatible array rvalue | allowed |
| CWG 589 | C++98 | a reference could not bind directly to an array or class rvalue | allowed |
| CWG 656 | C++98 | a reference to const-qualified type initialized with a type which is not reference-compatible but has a conversion function to a reference- compatible type was bound to a temporary copied from the return value (or its base class subobject) of the conversion function | bound to the return value (or its base class subobject) directly |
| CWG 1287 | C++11 | the conversion from *target* of class type to another reference-compatible type could only be implicit | allow explicit conversions |
| CWG 1295 | C++11 | a reference could bind to a bit-field xvalue | prohibited |
| CWG 1299 | C++98 | the definition of temporary was unclear | made clear |
| CWG 1571 | C++98 | user-defined conversions in indirect binding did not consider the type of *target* | considered |
| CWG 1604 | C++98 | user-defined conversions were not considered in indirect binding | considered |
| CWG 2352 | C++98 | reference compatibility did not consider qualification conversions | considered |
| CWG 2481 | C++17 | cv-qualification was not added to the result type of temporary materialization in indirect binding | added |
| CWG 2657 | C++17 | cv-qualification was not added to the result type of temporary materialization in direct binding | added |
| CWG 2801 | C++98 | reference-related types were allowed for indirect binding | prohibited |

### See also

- [constructor](https://en.cppreference.com/w/cpp/language/initializer_list)
- [converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor)
- [copy assignment](https://en.cppreference.com/w/cpp/language/as_operator)
- [copy constructor](https://en.cppreference.com/w/cpp/language/copy_constructor)
- [`explicit`](https://en.cppreference.com/w/cpp/language/explicit)
- [initialization](https://en.cppreference.com/w/cpp/language/initialization)
  - [constant initialization](https://en.cppreference.com/w/cpp/language/constant_initialization)
  - [copy initialization](https://en.cppreference.com/w/cpp/language/copy_initialization)
  - [direct initialization](https://en.cppreference.com/w/cpp/language/direct_initialization)
  - [list initialization](https://en.cppreference.com/w/cpp/language/list_initialization)
- [move assignment](https://en.cppreference.com/w/cpp/language/move_assignment)
- [move constructor](https://en.cppreference.com/w/cpp/language/move_constructor)
- [`new`](https://en.cppreference.com/w/cpp/language/new)

## Podcast Host Debate & Socratic Standard Traps

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

- Contrast raw storage duration with actual C++ object lifetime—and why malloc doesn't invoke constructors.
- Walk through why range-based for loops with temporary wrappers dangled for 12 years until C++23 P2718.
- Explain why strict aliasing breaks pointer-punning casts and how std::bit_cast solves it cleanly.

### Trap 1: [stmt.ranged] & P2718R0 (cppcon-stage)

Under C++17/C++20 rules, what happens in for (int x : make_holder().vec) if make_holder() returns a Holder by value?

```cpp
struct Holder { std::vector<int> vec{1, 2, 3}; };
Holder make_holder();
for (int x : make_holder().vec) { /* ... */ }
```

A. Safe in C++17 because the range-for __range reference extends Holder
B. Undefined behavior in C++17/C++20 because __range binds to .vec, leaving the Holder temporary to die before the loop body
C. Does not compile because vector cannot be copied
D. Extends Holder only when using auto&& x

**Standard Answer (B):** Undefined behavior in C++17/C++20 because __range binds to .vec, leaving the Holder temporary to die before the loop body

**Why:** In C++11–C++20, the range-for desugaring binds auto&& __range = make_holder().vec;. Because __range binds to the member subobject rather than the whole Holder temporary, the Holder temporary is destroyed at the semicolon of the __range declaration! C++23 (P2718R0) patched this rule specifically for range-for.

*CppCon speaker note:* One of the most famous real-world C++ bugs—even standard committee members tripped on it.

### Trap 2: [basic.life] & [ptr.launder] (standard-lawyer)

After destroying and placement-new constructing a struct containing a const int member in the same storage, how must you access the new object through the old pointer p?

```cpp
struct X { const int n; };
X* p = new X{1};
p->~X();
new (p) X{2};
```

A. p->n directly is always valid once placement new completes
B. std::launder(p)->n is required because X contains a const non-static data member
C. reinterpret_cast<X*>(p)->n avoids the requirement
D. Reusing storage containing a const member is impossible even with std::launder

**Standard Answer (B):** std::launder(p)->n is required because X contains a const non-static data member

**Why:** [basic.life]/8 states an old pointer automatically refers to the new object ONLY if the type has no const or reference non-static data members (among other rules). Otherwise, you must obtain the new pointer via placement new's return value or std::launder(p).

### Trap 3: [stmt.jump] & [class.dtor] (subtle)

In a single block { Guard a; Guard b; }, in what order are destructors invoked upon normal exit or an exception thrown after b is constructed?

A. a then b (construction order)
B. b then a (strict reverse order of construction)
C. Unspecified by the standard
D. Destructors are skipped if an exception unwinds

**Standard Answer (B):** b then a (strict reverse order of construction)

**Why:** Automatic local objects and class member subobjects are ALWAYS destroyed in exact reverse order of construction completion (LIFO), enabling dependent RAII guards like b holding a handle into a.

### Trap 4: [basic.lval] §7.2.1/11 & [bit.cast] (standard-lawyer)

Which method inspects the IEEE-754 bit pattern of a float as a uint32_t without violating C++ strict aliasing rules?

```cpp
float f = 3.14f;
```

A. uint32_t bits = *reinterpret_cast<uint32_t*>(&f);
B. union Pun { float f; uint32_t u; } p{f}; uint32_t bits = p.u;
C. auto bits = std::bit_cast<uint32_t>(f);
D. *(uint32_t*)(void*)&f

**Standard Answer (C):** auto bits = std::bit_cast<uint32_t>(f);

**Why:** Reading a float through a uint32_t* via reinterpret_cast violates strict aliasing ([basic.lval]), and reading an inactive union member is UB in C++ (unlike C99). C++20 std::bit_cast<uint32_t>(f) (or std::memcpy pre-C++20) is completely well-defined and constexpr.

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