skip to content

Perfect Forwarding

A T&& in a template is a forwarding reference, and std::forward keeps an argument's category on the way through. Senior interviews ask how emplace_back forwards.

on this pageshow

explore

questions

5

In C++, when is a parameter declared T&& a forwarding reference rather than an ordinary rvalue reference?

level: middleimportance: must knowfreq 65%

answer

  1. deduced right at this call
  2. exactly T&&, no const
  3. class template parameters are fixed
  4. lvalue argument deduces T as U&

basics

~20 s

T&& is a forwarding reference only when T belongs to that function template, is deduced from the call, and the parameter is exactly T&& with no const; auto&& behaves alike. const T&&, std::vector<T>&& and a class template's T&& are rvalue references.

solid answer

~40 s

The standard defines a **forwarding reference** as an rvalue reference to a cv-unqualified template parameter that does not represent a class template's parameter during class template argument deduction. Its special deduction rule: for an lvalue argument of type `A`, `T` is deduced as `A&`, so `T&&` collapses to `A&` and binds the lvalue; for an rvalue, `T` is `A` and the parameter is `A&&`. So `template<class T> void f(T&& x)` accepts `f(i)` with `T = int&`. Not forwarding references: `const T&&`, `std::vector<T>&&` (the parameter is not bare `T`), and `void put(T&&)` inside `template<class T> struct Box`, where `T` was fixed when the class was instantiated - which is why `std::vector<T>::push_back(T&&)` refuses a named element. `auto&& x = expr;` deduces by the same rule.

code

cpp · 25 lines
cpp
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

template <class T> void fwd(T&&) {
    std::cout << (std::is_lvalue_reference_v<T> ? "T = U&" : "T = U") << '\n';
}
template <class T> struct Box {
    std::vector<T> items;
    void put(T&& x) { items.push_back(static_cast<T&&>(x)); }   // rvalue reference
    template <class U> void emplace(U&& x) { items.emplace_back(static_cast<U&&>(x)); }
};

int main() {
    std::string s = "core";
    fwd(s);                    // lvalue: T deduced as std::string&
    fwd(std::string("net"));   // rvalue: T deduced as std::string
    auto&& r = s;              // deduces std::string&
    static_assert(std::is_same_v<decltype(r), std::string&>);
    Box<std::string> b;
    b.emplace(s);              // U&& is a forwarding reference: accepts the lvalue
    b.put(std::string("io"));  // T&& accepts only rvalues; b.put(s) would not compile
    std::cout << b.items.size() << '\n';
}

go deeper

for a junior

Recognise the shape: template<class T> void f(T&& x) takes anything, while a T&& whose T was fixed earlier takes only rvalues.

for a middle

State the three conditions - bare T, deduced at this call, no cv - and the U& deduction for lvalue arguments that collapses the parameter to U&.

for a senior

Classify the hard cases on sight: class template members, member templates, const T&&, auto&&, deduction guides, and explain push_back versus emplace_back.

for a principal

Weigh where a forwarding reference is the right API shape against a concrete overload pair, given how greedily it competes in overload resolution.

## The definition `&&` after a type has two meanings in C++, and only the context tells them apart. The C++ draft defines a **forwarding reference** as "an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction)". Three conditions follow: 1. The parameter's type is **exactly** `T&&`, where `T` is a template parameter. 2. `T` is **deduced from this call** - it belongs to the function template being called, not to an enclosing class. 3. There is **no cv-qualifier**: `const T&&` is not a forwarding reference. Everything else spelled with `&&` is an ordinary **rvalue reference**, which binds only rvalues. ## The deduction rule that makes it special For an ordinary parameter, deduction strips references from the argument. For a forwarding reference the draft adds one rule: if the argument is an **lvalue** of type `A`, the type "lvalue reference to `A`" is used for deduction. So: - `int i; f(i);` deduces `T = int&`, and the parameter `T&&` becomes `int& &&`, which **reference collapsing** turns into `int&`. - `f(0);` deduces `T = int`, and the parameter is `int&&`. The same function template therefore binds lvalues and rvalues alike, and `T` records which one it got. That record is what `std::forward<T>` reads later. ## Look-alikes that are rvalue references | Declaration | Forwarding reference? | Why | |---|---|---| | `template<class T> void f(T&& x)` | yes | bare `T`, deduced from the call | | `template<class T> void f(const T&& x)` | no | cv-qualified | | `template<class T> void f(std::vector<T>&& v)` | no | the parameter is not bare `T` | | `template<class T> struct Box { void put(T&& x); };` | no | `T` was fixed when `Box<T>` was instantiated | | `template<class T> struct Box { template<class U> void put(U&& x); };` | yes | `U` belongs to the member template | | `auto&& x = expr;` | deduces like one | `auto` uses template argument deduction | | `void g(std::string&& s)` | no | no template at all | The `Box` row is the one interviews probe: `std::vector<T>::push_back(T&&)` is an ordinary rvalue reference overload, so `v.push_back(name)` with a named `std::string` calls `push_back(const T&)` instead, while `emplace_back(Args&&... args)` is a member function template whose `Args&&` are forwarding references. ## What the compiler says Passing a named object where only an rvalue reference is declared produces a plain error. For the three rejected cases, Clang 21 reports: - `template<class T> void take_const(const T&&)` called with a `std::string` lvalue: "candidate function [with T = std::string] not viable: expects an rvalue for 1st argument". - `template<class T> void vec(std::vector<T>&&)` called with a named vector: the same "expects an rvalue" note. - `Box<std::string>::put(T&&)` called with a named string: "rvalue reference to type ... cannot bind to lvalue". ## Why the name matters The separate name exists because "rvalue reference" misleads in templates: early C++11 writing called these *universal references*, and the standard's wording calls them **forwarding references**. The practical consequences: - A function declared `template<class T> void f(T&& x)` accepts **every** argument, so it competes in overload resolution with everything else - a hazard covered with forwarding pitfalls. - Inside it, `x` must be passed on with `std::forward<T>(x)`, never `std::move(x)`, because `x` may refer to a caller's lvalue. - A function meant to accept only rvalues needs a constraint or a concrete type; a bare `T&&` will not enforce it. ## Forwarding references across the standard library Once the shape is familiar it is everywhere in the standard library's declarations: - **`std::move` itself** is declared `template<class T> constexpr remove_reference_t<T>&& move(T&& t) noexcept;` - its parameter is a forwarding reference, which is why it accepts lvalues at all. - **`std::make_unique` and `std::make_shared`** take `Args&&... args`. - **`std::invoke`** is declared `invoke(F&& f, Args&&... args)`, forwarding both the callable and its arguments. - **`emplace_back`, `emplace` and `try_emplace`** are member function templates over `Args&&...`, unlike the class-parameter `push_back(T&&)` beside them. - **Range algorithms** commonly take the range as `R&& r`, so they accept both named containers and temporaries. Each of these binds an lvalue argument without copying it, and decides only later, through `std::forward`, whether the argument may be moved from.

  • Why does auto&& in a range-for loop work over a std::vector<bool> when auto& does not?
    Dereferencing a `std::vector<bool>` iterator returns a proxy object by value, a prvalue. `auto&` is a non-const lvalue reference and cannot bind a prvalue, so it does not compile. `auto&&` deduces like a forwarding reference: for a prvalue it becomes an rvalue reference that binds the proxy, so the loop compiles and still writes through the proxy.
  • Is the T&& in a deduction guide such as template<class T> Box(T&&) -> Box<T>; a forwarding reference?
    Yes. The standard's exclusion covers only a class template's own parameter in an implicit guide made from a constructor during class template argument deduction. A user-written deduction guide's `T` is the guide's own template parameter, so `T&&` there is a forwarding reference; the draft's own example deduces `A<int&>` from an lvalue through such a guide.

  • Every T&& in a template is a forwarding reference.
  • const T&& is a forwarding reference that only adds const.
  • std::vector<T>::push_back(T&&) is a forwarding reference.
  • A forwarding reference deduces T as U&& for an rvalue argument.
  • Forwarding references only bind rvalues, like any other &&.
open as a page

In a C++ factory template<class T, class... Args> make_logger(Args&&... args), how do reference collapsing and std::forward<Args> preserve each argument's value category?

level: seniorimportance: must knowfreq 55%

basics

~20 s

For an lvalue argument Args is deduced as U&, so Args&& collapses to U& and std::forward<U&> returns an lvalue; for an rvalue Args is U, the parameter is U&&, and std::forward<U> returns an xvalue. The deduced type carries the category through.

open as a page

In C++, when do you write std::forward<T>(x) and when std::move(x) to pass an argument on?

level: juniorimportance: should knowfreq 60%

basics

~20 s

std::move(x) always yields an rvalue: use it on objects you own and no longer need. std::forward<T>(x) yields an rvalue only if the caller passed one: use it only on a forwarding reference T&& x in a template.

open as a page

In C++, why does the perfect-forwarding factory call make_logger<Logger>({"core", 3}, flush_hook) fail to compile when a direct Logger constructor call with the same arguments works?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A forwarding reference must deduce a type from each argument. A braced list has no type, and an overloaded function name like flush_hook names several functions, so deduction fails. The direct call works because the constructor's parameter types are already known.

open as a page

In C++, why does copying a non-const Logger call its template<class S> Logger(S&& name) constructor instead of the copy constructor, and how do you prevent it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

For a non-const Logger lvalue, S deduces as Logger&, giving Logger(Logger&) - a better match than the copy constructor's const Logger&, which adds const. Non-templates win only exact ties. Constrain the template, for example to types std::string is constructible from.

open as a page