skip to content

In C++, why can a const Point& parameter bind to a temporary while a Point& parameter cannot?

level: middleimportance: must knowfreq 70%

answer

  1. lvalues versus rvalues
  2. modifying a temporary is almost always a bug
  3. const& may create a temporary
  4. conversion means a different object

basics

~20 s

A non-const lvalue reference may bind only to a modifiable lvalue, because writing into a temporary that vanishes is almost always a mistake. A const lvalue reference may also bind to rvalues and to values needing a conversion, through a temporary.

solid answer

~40 s

The reference-binding rules split on `const`. A `Point&` must bind to an lvalue of a compatible type, so `normalize(Point{4, 2})` is rejected - Clang says the candidate "expects an lvalue" - and `double& d = count;` (an `int`) is rejected because it would need a converted copy. A `const Point&` accepts lvalues, prvalues such as `Point{4, 2}` or a function's return value, and even values of another type via conversion: the compiler materializes a temporary and binds to it. That is why `const T&` is the universal read-only parameter. The catch: when a conversion happens, the reference names a *new* object, so `const double& scaled = count;` does not see later changes to `count`. Binding rvalues for modification is what rvalue references are for, a separate topic.

code

cpp · 17 lines
cpp
#include <cstdio>

struct Point { double x, y; };

Point midpoint(const Point& a, const Point& b) { return {(a.x + b.x) / 2, (a.y + b.y) / 2}; }
void normalize(Point& p) { p.x /= 2; p.y /= 2; }   // in-out: needs a modifiable lvalue

int main() {
    Point a{0, 0};
    Point m = midpoint(a, Point{4, 2});   // const& binds to the temporary Point{4, 2}
    normalize(m);                          // OK: m is an lvalue
    // normalize(Point{4, 2});  // error: no matching function; candidate expects an lvalue
    int count = 3;
    const double& scaled = count;          // binds to a converted temporary double, not to count
    count = 10;
    std::printf("%.1f %.1f %.1f\n", m.x, m.y, scaled);
}

go deeper

for a junior

Recall that T& needs a named, modifiable object, while const T& also accepts temporaries and literals, which is why read-only parameters use const T&.

for a middle

Explain the binding rules by value category, the materialized temporary behind const T&, and why a conversion makes the reference name a different object.

for a senior

Spot hidden temporaries from implicit conversions in hot const& interfaces, use explicit constructors to block them, and keep in-out parameters as T& so misuse fails to compile.

for a principal

Fold the binding rules into the team's parameter conventions so read-only, in-out and consuming parameters each have one spelling that the compiler enforces.

## Value categories in one paragraph Every C++ expression is an **lvalue** (it designates an object with identity, such as a variable name `m` or `*ptr`) or an **rvalue** (a temporary value such as `Point{4, 2}`, `midpoint(a, b)` or `3.0`). The reference-binding rules in the standard decide which of these each kind of reference may bind to. The full taxonomy - prvalues, xvalues and rvalue references - belongs to the lesson on value categories; for lvalue references two rules are enough. ## Rule 1: a non-const lvalue reference needs a modifiable lvalue A `Point&` must be initialized by an lvalue whose type is `Point` or a class derived from it. It may not bind to: - a temporary: `normalize(Point{4, 2});` is rejected, and Clang's note reads "candidate function not viable: expects an lvalue for 1st argument"; - a function's by-value result: `normalize(midpoint(a, m));` is rejected the same way; - an object of another type that would need conversion: `double& d = count;` with `int count` fails with "non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'"; - a literal: `int& r = 5;` fails with "cannot bind to a temporary of type 'int'". The rationale is safety. A function that takes `Point&` announces it will modify the caller's object. If a temporary were accepted, the modification would land in an object that disappears at the end of the full-expression, and the caller would never see it - a silent bug. ## Rule 2: a const lvalue reference binds to almost anything A `const Point&` accepts: 1. lvalues of type `Point` (or derived), binding directly; 2. rvalues of type `Point`, such as `Point{4, 2}` or a function result - the prvalue is **materialized** into a temporary object and the reference binds to it; 3. values of other types that convert to `Point` implicitly - the compiler creates a temporary `Point` from the converted value and binds to that. Because the function promises not to modify the argument, binding a temporary is harmless. For a parameter, the temporary lives until the end of the full-expression containing the call, which covers the whole call. When a `const&` local variable binds a temporary, the temporary's lifetime is extended to the reference's; where that extension applies and where it silently does not is covered with temporaries and lifetime extension. ## The conversion surprise Rule 2's third case creates a **different object**: ```cpp int count = 3; const double& scaled = count; // binds to a temporary double 3.0 count = 10; // scaled is still 3.0 ``` The same happens with `const std::string& s = "literal";` - a `std::string` temporary is constructed - and with any implicit converting constructor. Code that takes `const T&` "to avoid a copy" therefore still pays for a conversion and a temporary when the caller passes a different type. Marking single-argument constructors `explicit` blocks the conversion and turns the hidden temporary into a compile error. ## A table to remember | Initializer | `Point&` | `const Point&` | |---|---|---| | lvalue `Point` (`m`) | binds directly | binds directly | | lvalue of derived class | binds to the base subobject | binds to the base subobject | | prvalue `Point{4, 2}` | ill-formed | binds to a materialized temporary | | value of another convertible type | ill-formed | binds to a converted temporary | | `const Point` lvalue | ill-formed (drops const) | binds directly | ## How this shapes APIs - Read-only parameters of expensive types are `const T&` precisely because callers can pass temporaries and literals. - In-out parameters are `T&`, and the compiler enforces that callers pass a real object. - An API that wants to accept temporaries **and** modify or steal from them uses an rvalue reference overload - that is the move-semantics material, and the reason `T&&` exists. - When a temporary must be modified - a scratch buffer handed to a helper - name it first (`Point tmp = make(); normalize(tmp);`); the extra line documents that the result is intentionally discarded.

  • Why does const std::string& name = "KataJob"; compile, and what does it cost?
    A string literal is an array of `const char`, not a `std::string`, so the `const&` cannot bind directly. The compiler constructs a temporary `std::string` through the converting constructor and binds the reference to it, possibly allocating. A function taking `const std::string&` pays that conversion on every call with a literal; `std::string_view` avoids it, which is covered with string views.
  • How long does a temporary bound to a const& function parameter live?
    Until the end of the full-expression that contains the call - typically the end of the statement. That covers the whole call, so using the parameter inside the function is safe. Returning that reference out of the function is not: the caller would hold a reference to a temporary that has already been destroyed.

  • A Point& parameter accepts temporaries if the function does not modify them
  • const double& d = some_int; makes d track later changes to the int
  • const& parameters never cost a copy or conversion
  • Binding a non-const reference to a temporary is a warning, not an error