# Forwarding References and Perfect Forwarding

> Decode the T&& template deduction exception, reference collapsing rules, and why std::forward and C++23 std::forward_like preserve exact value category and constness.

- **Source:** C++ Atlas (https://cppatlas.com/topics/forwarding-references-and-perfect-forwarding)
- **Track:** Templates
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [dcl.ref] (https://eel.is/c++draft/dcl.ref), [dcl.init.ref] (https://eel.is/c++draft/dcl.init.ref), [temp.deduct.call] (https://eel.is/c++draft/temp.deduct.call), [dcl.type.auto.deduct] (https://eel.is/c++draft/dcl.type.auto.deduct), [forward] (https://eel.is/c++draft/forward), [temp.variadic] (https://eel.is/c++draft/temp.variadic)
- **cppreference links:** [Template argument deduction](https://en.cppreference.com/w/cpp/language/template_argument_deduction), [Reference declaration](https://en.cppreference.com/w/cpp/language/reference), [Reference initialization](https://en.cppreference.com/w/cpp/language/reference_initialization), [std::forward](https://en.cppreference.com/w/cpp/utility/forward), [std::forward_like](https://en.cppreference.com/w/cpp/utility/forward_like), [std::move](https://en.cppreference.com/w/cpp/utility/move), [Placeholder type specifiers](https://en.cppreference.com/w/cpp/language/auto)
- **Prerequisites:** value-categories, type-deduction-auto-decltype, reference-binding-and-temporaries

Generic factories, wrappers, and `emplace` methods must pass arguments along to an inner constructor or function without copying lvalues or blocking moves on rvalues. Perfect forwarding achieves that by encoding the caller's value category inside a deduced template type parameter and restoring it at the forwarding boundary.

## When T&& is a forwarding reference (and when it isn't)

Despite sharing syntax with rvalue references, `T&&` becomes a **forwarding reference** (colloquially called a universal reference) only under an exact syntactic condition (`[temp.deduct.call]`): `T` must be a cv-unqualified template type parameter **of that specific function template**, written directly in the form `T&&` (or `auto&&` in variable declarations and generic lambda parameters).

Any cv-qualifier, wrapper type, or enclosing class-template parameter turns `&&` back into a strict rvalue reference that rejects lvalues:

```cpp
#include <vector>

template <class T>
void relay(T&& arg);                // forwarding reference: T is deduced here

template <class T>
void fixed(const T&& arg);          // plain rvalue reference: const disqualifies it

template <class T>
void wrap(std::vector<T>&& arg);    // plain rvalue reference: not bare T&&

template <class T>
struct Box {
    void push(T&& item);            // plain rvalue reference: T comes from Box<T>!
    template <class... Args>
    void emplace(Args&&... args);   // forwarding reference pack: Args deduced per call
};
```

> **Pitfall.** Writing `void push(T&&)` inside `template <class T> struct Box` does **not** declare a forwarding reference. By the time `push` is called on a `Box<Widget>`, `T` is already fixed to `Widget`, so `push` accepts only rvalues. Only a member function template with its own deduced parameter (`Args&&...`) forwards both lvalues and rvalues.

## The deduction exception and reference collapsing

Ordinarily, template argument deduction strips top-level references from parameter patterns. Forwarding references receive a deliberate exception in `[temp.deduct.call]`:

- When the call argument is an **lvalue** of type `U`, `T` is deduced as an **lvalue reference `U&`**.
- When the call argument is an **rvalue** (prvalue or xvalue) of type `U`, `T` is deduced as the non-reference type **`U`**.

C++ forbids writing a reference-to-reference directly in source (`int& &`), yet template substitution, type aliases, and `decltype` routinely produce them. Under `[dcl.ref]`, **reference collapsing** reduces every reference-to-reference pair by one rule: lvalue reference `&` is infectious. Combining `&` with `&`, `&` with `&&`, or `&&` with `&` yields `&`; only `&&` combined with `&&` remains `&&`.

| Call argument | Value category | Deduced `T` | Parameter `T&&` | `std::forward<T>(arg)` |
| --- | --- | --- | --- | --- |
| `Widget w;` | lvalue | `Widget&` | `Widget&` | `Widget&` (lvalue) |
| `const Widget cw;` | const lvalue | `const Widget&` | `const Widget&` | `const Widget&` (lvalue) |
| `Widget{}` | prvalue | `Widget` | `Widget&&` | `Widget&&` (xvalue) |
| `std::move(w)` | xvalue | `Widget` | `Widget&&` | `Widget&&` (xvalue) |

> **Mental model.** A forwarding reference uses `T` as a single-bit envelope recording whether the caller supplied an lvalue (`T = U&`) or an rvalue (`T = U`). Reference collapsing turns `T&&` into the exact parameter type needed to bind either one without copying.

## How std::forward and std::forward_like work

Inside `relay(T&& arg)`, the parameter `arg` has a name. Regardless of whether `arg` was bound to an lvalue or an rvalue, the expression `arg` inside the body is **always an lvalue**. Passing `arg` directly to another function would therefore invoke its copy overload even when the caller passed a temporary.

`std::forward<T>(arg)` unpacks the envelope stored in `T` by computing `static_cast<T&&>(arg)`:

- If the caller passed an lvalue, `T` is `Widget&`, so `static_cast<Widget& &&>(arg)` collapses to `static_cast<Widget&>(arg)`—an lvalue.
- If the caller passed an rvalue, `T` is `Widget`, so `static_cast<Widget&&>(arg)` casts the named lvalue back into an xvalue, enabling moves.

Notice why you must always supply `<T>` explicitly (`std::forward<T>(arg)`): `std::forward`'s parameter uses `std::remove_reference_t<T>&` (a non-deduced context) specifically so deduction cannot look at `arg`—which is always an lvalue—and erase the caller's value category. Furthermore, `[forward]` includes a second overload taking `remove_reference_t<T>&&` with a mandated static check ensuring `!std::is_lvalue_reference_v<T>`, so `std::forward<Widget&>(Widget{})` is rejected at compile time rather than returning a dangling lvalue reference to a temporary.

When forwarding a **member or subobject** of a forwarded aggregate `Self&& owner`, C++23 adds `std::forward_like<Self>(owner.member)`. Simply writing `std::forward<Self>(owner).member` fails to move if `member` is a reference or if `Self`'s cv-qualification and value category must be merged onto `member` cleanly:

```cpp
#include <string>
#include <utility>

struct Holder {
    std::string& ref;
};

template <class Self>
decltype(auto) extract(Self&& owner) {
    // Merges Self's constness and value category onto owner.ref
    return std::forward_like<Self>(owner.ref);
}
```

If `owner` is a `Holder&&`, `extract` yields `std::string&&`; if `owner` is `const Holder&&`, it yields `const std::string&&`; if `owner` is `const Holder&`, it yields `const std::string&`.

## Variadic forwarding and universal traps

Real factory wrappers combine forwarding references with parameter packs (`template <class... Args> auto make(Args&&... args) { return Target(std::forward<Args>(args)...); }`). Three sharp pitfalls arise in practice:

1. **Greedy forwarding constructors:** A single-argument template constructor `template <class S> Person(S&& name)` beats `Person(const Person&)` whenever you copy-construct from a **non-const** lvalue `Person p1; Person p2(p1);`. `S` deduces to `Person&` (an exact match), whereas `Person(const Person&)` requires adding `const`. Guard forwarding constructors with concepts (`requires (!std::same_as<std::remove_cvref_t<S>, Person>)`).
2. **Non-deduced braced-init-lists:** Calling `relay({1, 2, 3})` fails to deduce `T`. Unlike `auto x = {1, 2, 3};` (which has a special rule deducing `std::initializer_list<int>`), a braced-init-list is a non-deduced context for template parameter `T` (`[temp.deduct.call]`).
3. **Double forwarding:** Never call `std::forward<T>(arg)` twice on the same parameter in sequence. The first forwarded call may steal `arg`'s resources when the caller passed an rvalue, leaving the second call reading a moved-from object.

> **Standardese.** Under `[temp.deduct.call]`, a braced-init-list `{...}` matches a function template parameter only if that parameter explicitly names `std::initializer_list<U>` or an array/aggregate pattern—never a bare forwarding parameter `T&&`.

## What to remember

- `T&&` is a forwarding reference only when `T` is a cv-unqualified template parameter deduced by that exact function template (or `auto&&`), never `const T&&`, `Vec<T>&&`, or a class template's `T&&`.
- Lvalues deduce `T = U&` and rvalues deduce `T = U`; reference collapsing makes `&` win over `&&` in every combination.
- Named parameters are always lvalues; `std::forward<T>(arg)` restores xvalue-ness only when `T` is non-reference, and rejects forwarding an rvalue as an lvalue reference.
- Use C++23 `std::forward_like<Self>(member)` when forwarding a member or reference field according to its owner's constness and value category.
- Constrain single-argument forwarding constructors so they do not hijack non-const lvalue copies, and remember braced `{...}` arguments cannot deduce `T`.

## Concept Map Outline

- **Forwarding References:** Perfect forwarding encodes the caller's value category into a deduced type T and unpacks it with std::forward.
  - **Syntactic Conditions:** Only bare cv-unqualified T&& deduced at that function call acts as a forwarding reference.
    - **Deduced Function T&&:** T must be a template parameter of the function itself written directly as T&&.
    - **auto&& Variables & Lambdas:** auto&& obeys the exact same template deduction and collapsing rules for variables and generic lambdas.
    - **Disqualified Forms:** const T&&, vector<T>&&, and class-template Box<T>::push(T&&) are plain rvalue references.
  - **Deduction & Collapsing:** A special deduction rule pairs with reference collapsing to bind both lvalues and rvalues.
    - **Lvalue Deduces T&:** Passing an lvalue U deduces T as U&, making T&& collapse to U&.
    - **Rvalue Deduces T:** Passing a prvalue or xvalue U deduces T as U, leaving T&& as U&&.
    - **Infectious Lvalue Collapse:** Any reference-to-reference containing & collapses to &; only && plus && stays &&.
  - **Forwarding Mechanics:** Named parameters become lvalues inside bodies and must be cast back selectively.
    - **Named Param Is Lvalue:** Every named function parameter—even typed Widget&&—acts as an lvalue expression inside the body.
    - **std::forward Cast:** std::forward<T>(arg) performs static_cast<T&&>(arg) and forbids turning rvalues into lvalue refs.
    - **C++23 forward_like:** std::forward_like<Self>(member) transfers Self's constness and value category onto a subobject or ref.
  - **Variadic Forwarding:** Parameter packs forward arbitrary argument lists intact into constructors and factories.
    - **Pack Expansion:** Writing std::forward<Args>(args)... forwards every argument with its independent value category.
    - **Non-Deduced Braces:** Braced initializer lists like {1, 2} cannot deduce T&& and fail template deduction.
  - **Common Traps:** Unconstrained forwarding signatures silently steal copies or introduce double-move bugs.
    - **Greedy Copy Hijack:** An unconstrained T&& constructor beats const T& when copying a non-const lvalue.
    - **Double Forward Bug:** Forwarding the same parameter twice can read from an already moved-from rvalue.
    - **Dangling Forwarded Ref:** Returning a forwarded rvalue reference from a local temporary creates immediate dangling.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.deduct.call])

Which parameter declaration actually behaves as a forwarding reference capable of binding both lvalues and rvalues?

A. template <class T> void f(const T&& x);
B. template <class T> void f(std::vector<T>&& x);
C. template <class T> struct Holder { void put(T&& x); };
D. template <class T> void f(T&& x);

**Answer (D):** template <class T> void f(T&& x);

**Why:** Under [temp.deduct.call], T&& is a forwarding reference only when T is a cv-unqualified template parameter deduced for that exact function call. Adding const, wrapping in vector<T>, or using an enclosing class template's T produces a plain rvalue reference.

### Question 2 [warmup] ([temp.deduct.call], [dcl.ref])

Given `template <class T> void relay(T&& arg)` called with `int count = 7; relay(count);`, what are T, the declared type of arg, and the value category of expression `arg` inside relay?

A. T is int&, arg has type int&, and expression arg is an lvalue
B. T is int, arg has type int&&, and expression arg is an xvalue
C. T is int&, arg has type int&&, and expression arg is an lvalue
D. T is int, arg has type int&, and expression arg is a prvalue

**Answer (A):** T is int&, arg has type int&, and expression arg is an lvalue

**Why:** Passing an lvalue `count` deduces T = int& ([temp.deduct.call]). Reference collapsing turns T&& (int& &&) into int& ([dcl.ref]), and as a named variable `arg` is an lvalue.

### Question 3 [tricky] ([over.match.best], [temp.deduct.call])

Why does constructing `p2` from non-const `p1` fail to compile (or select the wrong constructor) below?

```cpp
struct Person {
    std::string name;
    template <class S>
    explicit Person(S&& s) : name(std::forward<S>(s)) {}
    Person(const Person& other) = default;
};
Person p1{"Ada"};
Person p2(p1);
```

A. Defaulted copy constructors cannot coexist with template constructors
B. Person(S&&) is explicit while copy construction requires an implicit constructor
C. The template constructor deduces S = Person&, which is an exact match that beats Person(const Person&)'s qualification conversion
D. std::forward<Person&>(p1) returns a moved-from Person

**Answer (C):** The template constructor deduces S = Person&, which is an exact match that beats Person(const Person&)'s qualification conversion

**Why:** Because `p1` is a non-const `Person` lvalue, `Person(S&&)` instantiates `Person(Person&)`, which requires no `const` qualification conversion and beats `Person(const Person&)` in overload resolution—then fails trying to construct `std::string` from `Person&`.

### Question 4 [tricky] ([temp.deduct.call])

What happens when calling `forward_to_vec({1, 2, 3})` where `forward_to_vec` takes `T&&`?

```cpp
void take_vec(std::vector<int> v);
template <class T>
void forward_to_vec(T&& arg) {
    take_vec(std::forward<T>(arg));
}
// forward_to_vec({1, 2, 3});
```

A. T deduces to std::initializer_list<int>, constructing std::vector<int>
B. Compilation fails because a braced-init-list is a non-deduced context for T&&
C. T deduces to int[3] and converts to std::vector<int>
D. Compiles only if T&& is replaced with const T&

**Answer (B):** Compilation fails because a braced-init-list is a non-deduced context for T&&

**Why:** Unlike `auto x = {1, 2, 3};`, template deduction against a bare `T&&` parameter cannot deduce `std::initializer_list` from a braced-init-list ({...} is a non-deduced context under [temp.deduct.call]).

### Question 5 [standardese] ([forward], [temp.deduct.type])

Why does `std::forward<T>(arg)` use `std::remove_reference_t<T>&` in its parameter instead of deducing `T` from `arg` automatically?

A. Inside the forwarding function, `arg` is always an lvalue; deducing T from `arg` would always yield an lvalue reference and lose whether the caller passed an rvalue
B. Template parameters can never be deduced for functions inside namespace std
C. std::remove_reference_t<T>& prevents std::forward from accepting const objects
D. Automatic deduction would trigger copy elision on `arg`

**Answer (A):** Inside the forwarding function, `arg` is always an lvalue; deducing T from `arg` would always yield an lvalue reference and lose whether the caller passed an rvalue

**Why:** By placing `T` inside the non-deduced type `std::remove_reference_t<T>&`, `[forward]` forces callers to pass the outer deduced `T` explicitly—preserving the distinction between `T = U&` (caller gave lvalue) and `T = U` (caller gave rvalue).

### Question 6 [standardese] ([forward])

What does the C++ standard specify for `std::forward<int&>(42)`?

```cpp
int& bad() {
    return std::forward<int&>(42);
}
```

A. Returns a dangling int& bound to temporary 42
B. Implicitly converts 42 into a static storage int so the reference stays valid
C. Ill-formed: the rvalue overload of std::forward mandates `!std::is_lvalue_reference_v<T>`
D. Returns an int prvalue by decaying the reference

**Answer (C):** Ill-formed: the rvalue overload of std::forward mandates `!std::is_lvalue_reference_v<T>`

**Why:** Under [forward], the overload `template<class T> constexpr T&& forward(remove_reference_t<T>&& t)` mandates that `is_lvalue_reference_v<T>` is `false`. Passing an rvalue (`42`) while requesting an lvalue-reference `T` (`int&`) is explicitly ill-formed.
