skip to content

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%

answer

  1. deduction encodes the category in Args
  2. & wins over &&
  3. forward returns static_cast<T&&>
  4. the same pattern as make_unique

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.

solid answer

~40 s

Deduction stores the caller's category in each `Args`: `U&` for an lvalue, plain `U` for an rvalue. **Reference collapsing** then fixes the parameter type: forming a reference to a reference yields an lvalue reference if either is `&`, and an rvalue reference only for `&&` on `&&`. So the parameter is `U&` or `U&&`, and either way the name `args` is an lvalue inside the body. `std::forward<Args>(args)` is specified as `static_cast<Args&&>(args)`: with `Args = U&` that is `U&` again, an lvalue; with `Args = U` it is `U&&`, an xvalue. The constructor therefore sees exactly what the caller passed. The standard library uses the same pattern: `std::make_unique` is specified as `unique_ptr<T>(new T(std::forward<Args>(args)...))`, and `emplace_back` forwards its arguments to the element's constructor.

code

cpp · 25 lines
cpp
#include <iostream>
#include <memory>
#include <string>
#include <utility>

struct FileSink {
    std::string path;
    int level;
    FileSink(const std::string& p, int l) : path(p), level(l) { std::cout << "  copied path\n"; }
    FileSink(std::string&& p, int l) : path(std::move(p)), level(l) { std::cout << "  moved path\n"; }
};

template <class T, class... Args>
std::unique_ptr<T> make_logger(Args&&... args) {
    return std::make_unique<T>(std::forward<Args>(args)...);
}

int main() {
    std::string path = "core.log";
    std::cout << "lvalue path:\n";
    auto a = make_logger<FileSink>(path, 1);
    std::cout << "temporary path:\n";
    auto b = make_logger<FileSink>(std::string("net.log"), 2);
    std::cout << "caller still has: " << path << '\n';
}

go deeper

for a junior

Know that a factory like make_unique passes its arguments on with std::forward so temporaries are moved and named objects are copied.

for a middle

Walk through deduction - U& for lvalues, U for rvalues - and the collapsing table that turns the parameter into U& or U&&.

for a senior

Read std::forward's two overloads, explain the non-deduced context and the Mandates guard, and trace a factory call through to the selected constructor.

for a principal

Decide where generic factories earn their place in a codebase versus explicit constructors, given that forwarding changes overload resolution for every caller.

## The four collapsing cases C++ forbids writing a reference to a reference directly, but one can arise through a template parameter, a `typedef` or `decltype`. The draft's rule - **reference collapsing** - says that if `TR` is a reference to `T`, then "lvalue reference to `TR`" is `T&`, and "rvalue reference to `TR`" is `TR` itself: | `TR` | `TR&` | `TR&&` | |---|---|---| | `U&` | `U&` | `U&` | | `U&&` | `U&` | `U&&` | In short: an lvalue reference anywhere wins, and only `&&` on `&&` stays `&&`. ## Step by step through make_logger Take the factory and a sink class with two constructors: ```cpp struct FileSink { FileSink(const std::string& path, int level); // copies path FileSink(std::string&& path, int level); // moves path }; template <class T, class... Args> std::unique_ptr<T> make_logger(Args&&... args) { return std::make_unique<T>(std::forward<Args>(args)...); } ``` For `make_logger<FileSink>(path, 2)` with a named `std::string path`: 1. `path` is an lvalue, so the first `Args` is deduced as `std::string&`; `2` is a prvalue, so the second is `int`. 2. The parameters become `std::string& &&` and `int&&`, which collapse to `std::string&` and `int&&`. 3. `std::forward<std::string&>(args)` is `static_cast<std::string& &&>`, collapsing to `std::string&` - an lvalue. 4. The `const std::string&` constructor is selected, and the caller's `path` is copied, not stolen. For `make_logger<FileSink>(std::string("net.log"), 2)` the first `Args` is `std::string`, the parameter is `std::string&&`, `std::forward<std::string>` yields `std::string&&` - an xvalue - and the moving constructor runs. ## Inside std::forward The standard declares two overloads: ```cpp template<class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept; template<class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept; ``` Both return `static_cast<T&&>(t)`. Three details matter: - The parameter type `remove_reference_t<T>&` puts `T` in a **non-deduced context**, so `T` must always be written explicitly. That is deliberate: the information is in the template argument, not in the expression. - The return type `T&&` is where collapsing happens; nothing at run time depends on it. - The second overload carries a Mandates clause - `is_lvalue_reference_v<T>` must be false - so forwarding an rvalue as an lvalue is a compile-time error. libc++ implements it as a `static_assert` with the message "cannot forward an rvalue as an lvalue". ## The same pattern in the standard library - **`std::make_unique<T>(args...)`** - specified as `unique_ptr<T>(new T(std::forward<Args>(args)...))`. - **`std::make_shared<T>(args...)`** - specified to give the object the initial value `T(std::forward<Args>(args)...)`. - **`emplace_back`, `emplace`, `try_emplace`** - declared as `template<class... Args> ... (Args&&... args)`; libc++'s `std::vector::emplace_back` passes `std::forward<_Args>(__args)...` down to the allocator's `construct`, which builds the element in place. - **`std::optional`'s `std::in_place` constructor** - forwards its arguments to the contained value's constructor. ## What "perfect" does and does not promise - It preserves **category and constness** of each argument, so overload resolution in the target sees what the caller wrote. - It does **not** avoid the copy or move inside the target constructor; it only avoids an extra one in the wrapper. - It works only when every argument has a **deducible type**; braced lists, overloaded function names and bit-fields break it, which is a separate topic. - Each argument may be forwarded **once**. Forwarding it to two constructors could move from it twice. ## Collapsing outside templates Collapsing is not a template-only rule; the draft states it for any reference formed through a `typedef` name, a template type parameter or a `decltype` specifier: ```cpp int i; typedef int& LRI; typedef int&& RRI; LRI&& r1 = i; // int& RRI& r2 = i; // int& RRI&& r3 = 5; // int&& ``` Forwarding references are simply the place where it matters most, because deduction deliberately produces `U&` to trigger it. ## Debugging a forwarding chain When a factory picks the wrong constructor, check each link in order: 1. **What did `Args` deduce?** A `static_assert(std::is_lvalue_reference_v<Args>)` inside the factory, or a deliberately failing instantiation, shows it in the compiler output. 2. **Is every use wrapped in `std::forward<Args>`?** A bare `args` copies; a `std::move(args)` steals. 3. **Is any argument forwarded twice?** A second use of a forwarded argument may see a moved-from object. 4. **Does the target have the overload you expect?** An instrumented constructor that prints "copied" or "moved", as in the code example, ends most arguments quickly.

  • Why must the template argument of std::forward be Args and not decltype(args) in make_logger?
    Inside the factory both work: `decltype(args)` is the declared parameter type, `U&` or `U&&`, and collapsing makes `std::forward<U&&>` behave like `std::forward<U>`. `Args` is the conventional spelling because it is the deduced type itself. `decltype(args)` becomes necessary only where there is no named template parameter, such as a generic lambda taking `auto&&`.
  • What does make_logger<FileSink>(std::as_const(path), 1) select, and why?
    `std::as_const(path)` is a `const std::string` lvalue, so `Args` is deduced as `const std::string&`. Forwarding yields a const lvalue, which only `FileSink(const std::string&, int)` accepts, so the path is copied. Constness is preserved along with category - that is part of what perfect forwarding means.

  • Args is deduced as std::string&& when the caller passes a temporary.
  • Reference collapsing makes U& && into U&&.
  • std::forward decides at run time whether to move.
  • Perfect forwarding means the target constructor never copies.
  • Forwarding the same argument to two calls is safe.