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?
answer
- S deduces as Logger&
- Logger& beats const Logger&
- templates lose only real ties
- constrain on what the body needs
basics
~20 sFor 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.
solid answer
~40 sOverload resolution compares `Logger(const Logger&)` with the template instantiated at `S = Logger&`, whose parameter collapses to `Logger&`. Binding a non-const lvalue to `Logger&` ranks better than binding it to `const Logger&`, so the non-template tie-breaker never applies. The template wins, and its body `name(std::forward<S>(n))` tries to build a `std::string` from a `Logger` - Clang reports "no matching constructor for initialization of 'std::string'" in `Logger::Logger<Logger &>`. A derived class copying its base with `Logger(other)` hits the same trap with `S = const FileLogger&`. Fix it with a constraint: in C++20, `requires std::constructible_from<std::string, S>`; in C++17, `std::enable_if_t` on `std::is_constructible_v`. Excluding only `Logger` itself, with `!std::same_as<std::remove_cvref_t<S>, Logger>`, still lets derived classes through.
code
cpp · 24 lines#include <concepts>
#include <iostream>
#include <string>
#include <utility>
struct Logger {
std::string name;
template <class S>
requires std::constructible_from<std::string, S>
explicit Logger(S&& n) : name(std::forward<S>(n)) { std::cout << "forwarding ctor\n"; }
Logger(const Logger& o) : name(o.name) { std::cout << "copy ctor\n"; }
};
struct FileLogger : Logger {
using Logger::Logger;
FileLogger(const FileLogger& o) : Logger(o) {}
};
int main() {
Logger a{std::string("core")};
Logger c{a}; // non-const lvalue: now the copy constructor
FileLogger f{"file"};
FileLogger g{f}; // derived copy reaches Logger's copy constructor
(void)c; (void)g;
}go deeper
Know that a constructor template taking T&& can be chosen when you copy an object, and that it needs a constraint.
Explain the deduction S = Logger& and why binding Logger& beats binding const Logger& for a non-const source.
Diagnose it from the instantiation note, include the derived-class copy case, and constrain on what the body needs rather than on the class name.
Set the team rule that single-argument forwarding constructors are always constrained, and back it with review checks or static analysis.
## The overload contest A class with a forwarding constructor and a copy constructor: ```cpp struct Logger { std::string name; template <class S> explicit Logger(S&& n) : name(std::forward<S>(n)) {} Logger(const Logger& o) : name(o.name) {} }; Logger a{std::string("core")}; Logger c{a}; // which constructor? ``` For `Logger c{a};` with a non-const `a`: 1. **The copy constructor** needs to bind `const Logger&` to a non-const lvalue - it adds `const`. 2. **The template** deduces `S = Logger&` (an lvalue argument to a forwarding reference), and `Logger& &&` collapses to `Logger&` - an exact match with nothing added. 3. The draft's ranking rule says that when two reference bindings differ only in cv-qualification, binding to the **less** cv-qualified type is better. So the template's conversion is strictly better. 4. The rule that prefers a non-template over a template specialization applies only when the conversions are otherwise **indistinguishable**, so it never comes into play. The template wins. Its body forwards a `Logger&` into `std::string`'s constructor, and the build fails with an error inside the class, far from the innocent-looking copy. ## Where it bites - **Copying a non-const object** - `Logger c{a};` always, and `Logger c = a;` or passing `a` to a by-value `Logger` parameter when the template constructor is not `explicit`. - **A derived class's copy constructor** - `FileLogger(const FileLogger& o) : Logger(o) {}` passes a `const FileLogger&`. The copy constructor of `Logger` needs a derived-to-base conversion; the template deduces `S = const FileLogger&` and matches exactly, so it wins even for a const source. - **Silent wrong behaviour.** If the member could be built from a `Logger` - say the template stored `S` into a `std::any` - the program would compile and do the wrong thing, which is worse than an error. A const source alone does not trigger it: `const Logger& ca = a; Logger b{ca};` is an exact match for both, and then the non-template copy constructor wins the tie. ## Fixes | Fix | Standard | Effect | |---|---|---| | `requires std::constructible_from<std::string, S>` | C++20 | the template exists only for arguments the body can use - excludes `Logger` and anything derived from it | | `template <class S, class = std::enable_if_t<std::is_constructible_v<std::string, S>>>` | C++11 traits, `_t`/`_v` helpers from C++14/C++17 | the same constraint through substitution failure | | `requires (!std::same_as<std::remove_cvref_t<S>, Logger>)` | C++20 | fixes `Logger c{a};` but not a derived class's copy | | add `Logger(Logger&)` | any | patches one case, doubles the copy constructors, leaves derived classes broken | Constraining on **what the body needs** is the robust choice: it states the template's real requirement and therefore rejects every type that would only have produced an error later. The mechanics of `requires`-clauses and `std::enable_if` belong to the material on constraints and SFINAE; the forwarding-specific lesson is that a bare `S&&` constructor accepts *every* single argument, including the class itself. ## Spotting it in review - A single-argument constructor template taking `T&&` with no constraint is a red flag on sight. - An error message naming `Logger::Logger<Logger &>` or `Logger::Logger<const FileLogger &>` is the signature of this bug. - The same hijack happens to a forwarding *assignment* operator template competing with copy assignment, and to any variadic `Args&&...` constructor called with one argument. ## Why the template is so greedy A forwarding reference deduces the **exact** type of whatever it receives, with exactly the received constness and category. Its conversion sequence is therefore always an identity binding: no `const` added, no derived-to-base conversion, no user-defined conversion. Any hand-written overload that needs even one of those adjustments loses to it. That is useful in a factory, where accepting everything is the point, and dangerous in a constructor, which competes with the copy and move constructors on every copy and move of the class. ## The C++17 spelling Code that cannot use C++20 constraints writes the same requirement with a defaulted template parameter: ```cpp template <class S, class = std::enable_if_t<std::is_constructible_v<std::string, S>>> explicit Logger(S&& n) : name(std::forward<S>(n)) {} ``` When `S` is `Logger&` or `const FileLogger&`, `std::is_constructible_v<std::string, S>` is `false`, `std::enable_if_t` has no type, substitution fails, and the template silently leaves the candidate set. This variant was compiled and run with Clang 21 in C++17 mode, alongside the C++20 one in the code example.
- Why does a const source not trigger the hijack?For a `const Logger` lvalue, `S` deduces as `const Logger&`, so both candidates bind `const Logger&` - identical conversions. With nothing else to separate them, the rule preferring a non-template function over a function template specialization applies, and the copy constructor wins.
- Does declaring the template constructor stop the compiler from declaring the implicit copy constructor?No. A constructor template is never a copy constructor, so a class with only a forwarding constructor template still gets an implicitly declared copy constructor. That is exactly why the two compete: the implicit `Logger(const Logger&)` exists, and the template beats it for non-const lvalues.
- Non-template functions always beat templates in overload resolution.
- A template constructor suppresses the implicit copy constructor.
- Excluding the exact class type with std::is_same fixes derived classes too.
- The hijack only happens when the source object is const.
- Marking the forwarding constructor explicit stops it from being used for copies.
Assumes C++23; requires-clauses, std::constructible_from and std::remove_cvref_t are C++20, and C++17 code expresses the same constraint with std::enable_if_t and std::is_constructible_v.