# Reference declaration

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

Declares a named variable as a reference, that is, an alias to an already-existing object or function.

## Executive Mental Model (Study Companion)

**Core Intuition:** T&& is a forwarding reference ONLY when T is a deduced template parameter of that exact function—not std::vector<T>&&.

- **Standard Era:** C++11 → C++20 → C++23
- **Primary ISO Clauses:** [dcl.ref], [temp.deduct.call], [class.copy.ctor], [utility.syn]
- **CppCon Talk Angle:** Show the exact 24-byte stack footprint of std::vector: copying duplicates the heap allocation, moving copies 3 pointers and nulls the source.
- **Common Audience Trap:** Forgetting noexcept on a custom move constructor, forcing std::vector::push_back to fall back to O(N) deep copies for exception safety.
- **Stage Takeaway:** Universal reference collapsing has one simple rule: '&' is infectious (& + anything = &). Only && + && yields &&.

## Memory Map Walkthrough: Stack/Heap Move Layout & Reference Collapsing Lab

Moving an owning container like std::vector does not move heap elements; it copies the 24-byte stack control block (begin, end, capacity pointers) into the destination and resets the source pointers to null in O(1) time. However, to preserve the strong exception guarantee during std::vector reallocation, std::vector calls std::move_if_noexcept—meaning if your user-defined move constructor is missing noexcept, vector silently copies every element instead of moving! Meanwhile, forwarding references (T&& or auto&&) leverage reference collapsing ([dcl.ref]): when an lvalue Widget passes to template<class T> void f(T&&), T deduces to Widget&, and Widget& && collapses to Widget&, letting std::forward<T> preserve the caller's exact value category.

### The noexcept move constructor cliff ([utility.move.if.noexcept] & [vector.capacity])

std::vector::push_back promises the strong exception guarantee: if reallocation fails halfway through migrating elements from the old buffer to the new buffer, the vector remains unchanged.

If moving element #50 out of 100 throws an exception, the old buffer already has 49 moved-from husks that cannot be rolled back. Therefore std::vector uses std::move_if_noexcept—it moves ONLY when the move constructor is noexcept (or when no copy constructor exists).

*noexcept unlocks fast vector growth:*
```cpp
struct Buffer {
    int* data = nullptr;
    Buffer(Buffer&& other) noexcept   // <-- omit noexcept and vector COPIES!
        : data(std::exchange(other.data, nullptr)) {}
    Buffer(const Buffer& other);
};
```

**Key takeaway:** Always mark user-defined move constructors and move assignment operators noexcept whenever they cannot throw.

### Forwarding reference vs. rvalue reference & collapsing ([temp.deduct.call] & [dcl.ref])

The syntax T&& means 'rvalue reference' everywhere EXCEPT when T is a deduced type parameter of that function template (or auto&&). Any cv-qualifier (const T&&) or wrapper (std::vector<T>&&) disables the forwarding-reference rule and becomes a plain rvalue reference.

When T&& IS a forwarding reference and receives an lvalue of type X, template deduction makes an intentional exception: T deduces to X&. Then reference collapsing fires: X& + && collapses to X&. Passing an rvalue deduces T = X, leaving X&&.

*Reference collapsing matrix:*
```cpp
template <class T>
void relay(T&& arg) {
    sink(std::forward<T>(arg));
}

Widget w;
relay(w);            // T = Widget&,  arg = Widget&  (lvalue)
relay(Widget{});     // T = Widget,   arg = Widget&& (xvalue after forward)
relay(std::move(w)); // T = Widget,   arg = Widget&&
```

**Key takeaway:** Any single & in a reference collapse (& &, & &&, && &) yields &; only && + && stays &&.

## Official Specification Summary (cppreference)

Declares a named variable as a reference, that is, an alias to an already-existing object or function.

### Syntax

A reference variable declaration is any simple declaration whose declarator has the form

- `&` *attr* (optional) *declarator*    (1)
- `&&` *attr* (optional) *declarator*    (2) (since C++11)

1) **Lvalue reference declarator**: the declaration `S& D;` declares `D` as an *lvalue reference* to the type determined by *decl-specifier-seq* `S`.

2) **Rvalue reference declarator**: the declaration `S&& D;` declares `D` as an *rvalue reference* to the type determined by *decl-specifier-seq* `S`.

- `declarator` - any declarator except another reference declarator (there are no references to references)
- `attr` - (since C++11) list of attributes

A reference is required to be initialized to refer to a valid object or function: see reference initialization.

The type “reference to (possibly cv-qualified) `void`” cannot be formed.

Reference types cannot be cv-qualified at the top level; there is no syntax for that in declaration, and if a qualification is added to a typedef-name or `decltype` specifier, (since C++11) or type template parameter, it is ignored.

References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics (e.g. a non-static data member of reference type usually increases the size of the class by the amount necessary to store a memory address).

Because references are not objects, there are no arrays of references, no pointers to references, and no references to references:

```cpp
int& a[3]; // error
int&* p;   // error
int& &r;   // error
```

(since C++11):

### Reference collapsing

It is permitted to form references to references through type manipulations in templates or typedefs, in which case the *reference collapsing* rules apply: rvalue reference to rvalue reference collapses to rvalue reference, all other combinations form lvalue reference:

```cpp
typedef int&  lref;
typedef int&& rref;
int n;

lref&  r1 = n; // type of r1 is int&
lref&& r2 = n; // type of r2 is int&
rref&  r3 = n; // type of r3 is int&
rref&& r4 = 1; // type of r4 is int&&
```

(This, along with special rules for template argument deduction when `T&&` is used in a function template, forms the rules that make `std::forward` possible.)

### Lvalue references

Lvalue references can be used to alias an existing object (optionally with different cv-qualification):

```cpp
#include <iostream>
#include <string>

int main()
{
    std::string s = "Ex";
    std::string& r1 = s;
    const std::string& r2 = s;

    r1 += "ample";           // modifies s
//  r2 += "!";               // error: cannot modify through reference to const
    std::cout << r2 << '\n'; // prints s, which now holds "Example"
}
```

They can also be used to implement pass-by-reference semantics in function calls:

```cpp
#include <iostream>
#include <string>

void double_string(std::string& s)
{
    s += s; // 's' is the same object as main()'s 'str'
}

int main()
{
    std::string str = "Test";
    double_string(str);
    std::cout << str << '\n';
}
```

When a function's return type is lvalue reference, the function call expression becomes an lvalue expression:

```cpp
#include <iostream>
#include <string>

char& char_number(std::string& s, std::size_t n)
{
    return s.at(n); // string::at() returns a reference to char
}

int main()
{
    std::string str = "Test";
    char_number(str, 1) = 'a'; // the function call is lvalue, can be assigned to
    std::cout << str << '\n';
}
```

(since C++11):

### Rvalue references

Rvalue references can be used to extend the lifetimes of temporary objects (note, lvalue references to const can extend the lifetimes of temporary objects too, but they are not modifiable through them):

```cpp
#include <iostream>
#include <string>

int main()
{
    std::string s1 = "Test";
//  std::string&& r1 = s1;           // error: can't bind to lvalue

    const std::string& r2 = s1 + s1; // okay: lvalue reference to const extends lifetime
//  r2 += "Test";                    // error: can't modify through reference to const

    std::string&& r3 = s1 + s1;      // okay: rvalue reference extends lifetime
    r3 += "Test";                    // okay: can modify through reference to non-const
    std::cout << r3 << '\n';
}
```

More importantly, when a function has both rvalue reference and lvalue reference overloads, the rvalue reference overload binds to rvalues (including both prvalues and xvalues), while the lvalue reference overload binds to lvalues:

```cpp
#include <iostream>
#include <utility>

void f(int& x)
{
    std::cout << "lvalue reference overload f(" << x << ")\n";
}

void f(const int& x)
{
    std::cout << "lvalue reference to const overload f(" << x << ")\n";
}

void f(int&& x)
{
    std::cout << "rvalue reference overload f(" << x << ")\n";
}

int main()
{
    int i = 1;
    const int ci = 2;

    f(i);  // calls f(int&)
    f(ci); // calls f(const int&)
    f(3);  // calls f(int&&)
           // would call f(const int&) if f(int&&) overload wasn't provided
    f(std::move(i)); // calls f(int&&)

    // rvalue reference variables are lvalues when used in expressions
    int&& x = 1;
    f(x);            // calls f(int& x)
    f(std::move(x)); // calls f(int&& x)
}
```

This allows move constructors, move assignment operators, and other move-aware functions (e.g. `std::vector::push_back()`) to be automatically selected when suitable.

Because rvalue references can bind to xvalues, they can refer to non-temporary objects:

```cpp
int i2 = 42;
int&& rri = std::move(i2); // binds directly to i2
```

This makes it possible to move out of an object in scope that is no longer needed:

```cpp
std::vector<int> v{1, 2, 3, 4, 5};
std::vector<int> v2(std::move(v)); // binds an rvalue reference to v
assert(v.empty());
```

### Forwarding references

Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to *forward* it by means of `std::forward`. Forwarding references are either:

1) function parameter of a function template declared as rvalue reference to cv-unqualified type template parameter of that same function template:

```cpp
template<class T>
int f(T&& x)                      // x is a forwarding reference
{
    return g(std::forward<T>(x)); // and so can be forwarded
}

int main()
{
    int i;
    f(i); // argument is lvalue, calls f<int&>(int&), std::forward<int&>(x) is lvalue
    f(0); // argument is rvalue, calls f<int>(int&&), std::forward<int>(x) is rvalue
}

template<class T>
int g(const T&& x); // x is not a forwarding reference: const T is not cv-unqualified

template<class T>
struct A
{
    template<class U>
    A(T&& x, U&& y, int* p); // x is not a forwarding reference: T is not a
                             // type template parameter of the constructor,
                             // but y is a forwarding reference
};
```

2) `auto&&` except when deduced from a brace-enclosed initializer list or, when representing a template parameter of a class template during class template argument deduction (since C++17):

```cpp
auto&& vec = foo();       // foo() may be lvalue or rvalue, vec is a forwarding reference
auto i = std::begin(vec); // works either way
(*i)++;                   // works either way

g(std::forward<decltype(vec)>(vec)); // forwards, preserving value category

for (auto&& x: f())
{
    // x is a forwarding reference; this is a common way to use range for in generic code
}

auto&& z = {1, 2, 3}; // *not* a forwarding reference (special case for initializer lists)
```

See also template argument deduction and `std::forward`.

### Dangling references

Although references always refer to valid objects or functions upon initialization, it is possible to create a program where the lifetime of the referred-to object ends, but the reference remains accessible (*dangling*).

Given an expression `expr` of reference type and let `target` be the object or function denoted by the reference:

- If a pointer to `target` would be valid in the context of the evalution of `expr`, the result designates `target`.
- Otherwise, the behavior is undefined.

```cpp
std::string& f()
{
    std::string s = "Example";
    return s; // exits the scope of s:
              // its destructor is called and its storage deallocated
}

std::string& r = f(); // dangling reference
std::cout << r;       // undefined behavior: reads from a dangling reference
std::string s = f();  // undefined behavior: copy-initializes from a dangling reference
```

Note that rvalue references and lvalue references to const extend the lifetimes of temporary objects (see Reference initialization for rules and exceptions).

If the referred-to object was destroyed (e.g. by explicit destructor call), but the storage was not deallocated, a reference to the out-of-lifetime object may be used in limited ways, and may become valid if the object is recreated in the same storage (see Access outside of lifetime for details).

### Type-inaccessible references

Attempting to bind a reference to an object where the converted initializer is an lvalue (until C++11) a glvalue (since C++11) through which the object is not type-accessible results in undefined behavior:

```cpp
char x alignas(int);

int& ir = *reinterpret_cast<int*>(&x); // undefined behavior:
                                       // initializer refers to char object
```

### Call-incompatible references

Attempting to bind a reference to a function where the converted initializer is an lvalue (until C++11) a glvalue (since C++11) whose type is not call-compatible with the type of the function's definition results in undefined behavior:

```cpp
void f(int);

using F = void(float);
F& ir = *reinterpret_cast<F*>(&f); // undefined behavior:
                                   // initializer refers to void(int) function
```

### Notes

| Feature-test macro | Value | Std | Feature |
| --- | --- | --- | --- |
| `__cpp_rvalue_references` | `200610L` | (C++11) | Rvalue references |

### 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 453 | C++98 | it was unclear which object or function a reference cannot be bound to | made clear |
| CWG 1510 | C++11 | cv-qualified references could not be formed in the operand of `decltype` | allowed |
| CWG 2550 | C++98 | parameters could have type “reference to `void`” | disallowed |
| CWG 2933 | C++98 | the behavior of accessing dangling references was unclear | made clear |

### External links

Thomas Becker, 2013 - C++ Rvalue References Explained

## Podcast Host Debate & Socratic Standard Traps

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

- Break down what std::vector actually puts on the stack versus the heap, and why moving a million-element vector costs three pointer assignments.
- Tell the story of the missing noexcept move constructor and how std::move_if_noexcept quietly saves exception safety at the cost of speed.
- Clarify why Box<T>::push(T&&) is NOT a forwarding reference even though T&& looks identical.

### Trap 1: [vector.modifiers] & [utility.move.if.noexcept] (cppcon-stage)

Widget defines BOTH a copy constructor and a non-noexcept move constructor. What does std::vector<Widget>::push_back invoke on existing elements during buffer growth?

```cpp
struct Widget {
    Widget(const Widget&);
    Widget(Widget&&); // Note: NOT marked noexcept
};
```

A. The move constructor, because std::vector always moves existing items
B. The copy constructor, via std::move_if_noexcept, to preserve the strong exception guarantee
C. Compile error: move constructors must be noexcept to live in std::vector
D. memcpy bitwise relocation

**Standard Answer (B):** The copy constructor, via std::move_if_noexcept, to preserve the strong exception guarantee

**Why:** Because Widget has a copy constructor and its move constructor might throw, std::move_if_noexcept yields const Widget& so std::vector copies elements safely into the new buffer before freeing the old buffer.

### Trap 2: [temp.deduct.call] §13.10.3.2 (standard-lawyer)

Which function parameter is actually a forwarding (universal) reference?

A. template<class T> void f(std::vector<T>&& v);
B. template<class T> void f(const T&& v);
C. template<class T> struct Box { void push(T&& v); };
D. auto&& x = expr;

**Standard Answer (D):** auto&& x = expr;

**Why:** std::vector<T>&& and const T&& are plain rvalue references. Box<T>::push(T&&) is NOT deduced at the push() call site because T was already fixed by Box<T>! Only auto&& (or a template function's own deduced T&&) is a forwarding reference.

*CppCon speaker note:* Box<T>::push(T&&) is a notorious class-template surprise (think std::vector<T>::push_back(T&&)).

### Trap 3: [dcl.ref] §9.3.4.3 (subtle)

Given using LRef = int&; and using RRef = int&&;, what type does LRef&& collapse to?

A. int&&
B. int&
C. int
D. Ill-formed: references to references are always illegal

**Standard Answer (B):** int&

**Why:** While writing int& && directly in source is illegal, forming a reference to a reference through type aliases, decltype, or template substitution collapses via [dcl.ref]: if either reference is an lvalue reference (&), the result is an lvalue reference (int&).

### Trap 4: [lib.types.movedfrom] (subtle)

After std::string b = std::move(a);, what operations are guaranteed valid on the moved-from string a?

A. a is guaranteed to be empty (a.empty() == true)
B. Only destruction and reassignment are valid; calling a.clear() is UB
C. a is in a valid but unspecified state: all operations with no preconditions (like a.empty(), a.clear(), a = "new", ~string) are valid
D. Using a in any way after std::move is Undefined Behavior

**Standard Answer (C):** a is in a valid but unspecified state: all operations with no preconditions (like a.empty(), a.clear(), a = "new", ~string) are valid

**Why:** Standard library types leave moved-from objects in a valid but unspecified state ([lib.types.movedfrom]). While small-string optimization means a might NOT even be empty, you may safely inspect size(), call clear(), reassign, or destroy a.

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