skip to content

In C++, given overloads f(const std::string&) and f(std::string&&), which one does each kind of argument select, and why?

level: middleimportance: must knowfreq 65%

answer

  1. which references accept which categories
  2. const T& accepts everything
  3. T&& refuses lvalues
  4. a tie-breaker ranks rvalue binding

basics

~20 s

An lvalue can bind only to const std::string&, so it selects that overload. An rvalue - a prvalue like make() or an xvalue like std::move(s) - can bind to both, and overload resolution prefers std::string&&. A const rvalue falls back to const std::string&.

solid answer

~40 s

Binding rules come first: a non-const `T&` binds only to non-const lvalues, `const T&` binds to lvalues and rvalues alike, and a non-const `T&&` binds only to non-const rvalues. So `f(s)` has one viable candidate, `f(const std::string&)`. For `f(std::move(s))` or `f(make())` both are viable, and a tie-breaker in the standard's ranking of implicit conversion sequences decides: binding an rvalue reference to an rvalue beats binding an lvalue reference. `f("literal")` first converts the literal to a temporary `std::string` for either overload, and the same tie-breaker picks `std::string&&`. `f(std::move(c))` with `const std::string c` yields a `const std::string&&` that `std::string&&` cannot accept, so it binds to `const std::string&`.

code

cpp · 18 lines
cpp
#include <iostream>
#include <string>
#include <utility>

void f(const std::string&) { std::cout << "const std::string&\n"; }
void f(std::string&&)      { std::cout << "std::string&&\n"; }

std::string make() { return "made"; }

int main() {
    std::string s = "hi";
    const std::string c = "const";
    f(s);             // lvalue
    f(std::move(s));  // xvalue
    f(make());        // prvalue
    f("literal");     // converted to a temporary std::string
    f(std::move(c));  // const xvalue
}

go deeper

for a junior

Remember the shape: T& takes named objects, const T& takes anything, and T&& takes temporaries and std::move results.

for a middle

Walk through overload resolution: first which overloads are viable for the argument's category, then the rule that prefers binding an rvalue reference to an rvalue.

for a senior

Predict the awkward cases - a string literal argument, a const xvalue, ref-qualified members - and explain why a T&&-only overload is an ownership statement.

for a principal

Judge when a team should write the const T& plus T&& pair, a single by-value parameter, or a T&&-only sink, and what each costs in overloads.

## Which reference binds to what A reference parameter is a promise about what the function may do with the argument, and the binding rules enforce that promise: | Parameter type | Non-const lvalue | Const lvalue | Non-const rvalue | Const rvalue | |---|---|---|---|---| | `T&` | binds | no | no | no | | `const T&` | binds | binds | binds | binds | | `T&&` | no | no | binds | no | | `const T&&` | no | no | binds | binds | The two "no" entries that matter most: - **A non-const lvalue reference refuses rvalues.** `std::string& a = make();` is ill-formed; Clang reports "non-const lvalue reference to type ... cannot bind to a temporary". Modifying a temporary through a reference would silently lose the change. - **An rvalue reference refuses lvalues of its type.** `std::string&& b = s;` is ill-formed ("rvalue reference ... cannot bind to lvalue"), because the callee may pillage the object and the caller still owns it. When an argument of a *different* type needs a conversion, a fresh temporary is created and the rvalue reference binds to that. `const T&` accepts everything, which is why C++98 code used it for every read-only parameter, and why it is the fallback whenever a `T&&` overload cannot take an argument. ## The tie-breaker When both `const std::string&` and `std::string&&` can bind an rvalue, overload resolution compares the two implicit conversion sequences. Both are identity conversions, so the standard needs a specific rule: when neither reference refers to the implicit object parameter of a member function declared without a ref-qualifier, a sequence that **binds an rvalue reference to an rvalue** is better than one that **binds an lvalue reference**. That rule is what makes move semantics work - every move constructor and move assignment operator is selected by it. ## Walking through five calls With `std::string s`, `const std::string c`, and `std::string make();`: 1. `f(s)` - lvalue. Only `const std::string&` is viable. Copy-side overload. 2. `f(std::move(s))` - xvalue. Both viable; the tie-breaker picks `std::string&&`. 3. `f(make())` - prvalue. Both viable; `std::string&&` again. 4. `f("literal")` - a `const char[8]` lvalue, but neither parameter is reference-related to it, so each binding creates a temporary `std::string` through the same converting constructor. The reference then binds to that temporary, an rvalue, so `std::string&&` wins. 5. `f(std::move(c))` - a `const std::string` xvalue. `std::string&&` would drop `const`, so only `const std::string&` is viable. The code example for this question prints exactly that sequence. ## The same rule on member functions Ref-qualified member functions apply the same idea to the object expression itself. A class can declare `void p() &;` and `void p() &&;`; `a.p()` on a named object calls the `&` version and `A().p()` on a temporary calls the `&&` version. The standard library uses this: `std::optional::value()` has a `&&` overload returning `T&&`, so the value of an expiring optional can be moved out instead of copied. ## Practical consequences - **The pair `const T&` + `T&&` is the classic sink overload set**, used by `std::vector::push_back` and by copy and move assignment. It costs two overloads per parameter. - **A single by-value parameter** (`void f(std::string s)`) gives the same binding behaviour with one function - lvalues are copied into it, rvalues moved - at the price of one extra move. That trade-off belongs to the parameter-passing material. - **Adding only `f(std::string&&)`** makes every lvalue call a compile error, which is sometimes exactly the intent: an API that must take ownership. - **`const T&&` overloads** are rare; they exist mostly to be deleted, so that a function refuses temporaries entirely. ## Common misreadings - **"`s` is a `std::string`, so it goes to the `std::string&&` overload."** The parameter type `std::string&&` names a type, but it only accepts rvalue expressions; the category of the argument, not its type, decides. - **"Temporaries cannot bind to references."** They cannot bind to non-const lvalue references; `const T&` and `T&&` accept them. - **"Two viable reference overloads are ambiguous."** Not when one binds an rvalue reference to an rvalue and the other binds an lvalue reference; the tie-breaker settles it. - **"`std::move` always reaches the `&&` overload."** A const argument keeps its `const`, and a non-const rvalue reference cannot bind it. Read every call by asking first which overloads can bind the argument at all, and only then which binding ranks higher.

  • If you delete f(const std::string&) and keep only f(std::string&&), what happens to f(s) for a named std::string s?
    It no longer compiles. `std::string&&` cannot bind to an lvalue of type `std::string`, and there is no other candidate, so the caller must write `f(std::move(s))` and visibly give up the string. Some APIs use exactly that to force callers to transfer ownership instead of copying by accident.
  • Why can a const std::string& parameter bind to a temporary when std::string& cannot?
    Among lvalue references, only one to a const, non-volatile type may bind to an rvalue, because writing to a temporary through a non-const reference would lose the change when the temporary dies. A `const` reference cannot write, so binding is harmless, and the temporary's lifetime is extended to match the reference's - a rule covered with temporaries.

  • f(s) picks std::string&& because s is a std::string.
  • A const std::string& parameter cannot accept a temporary.
  • f(make()) is ambiguous between the two overloads.
  • An rvalue reference can bind to any expression of its type.
  • std::move on a const string still selects the std::string&& overload.