In C++, why is `const std::string& name = doc.name();` safe when name() returns by value, and which references extend a temporary?
answer
- binding directly to the temporary
- const T& and T&& only
- a member of a temporary counts
- lives as long as the reference
basics
~20 sBinding a temporary directly to a const T& or T&& reference extends its lifetime to that reference's lifetime. A non-const lvalue reference cannot bind to it at all, and binding through a function that returns a reference extends nothing.
solid answer
~50 sWhen a reference is initialized **directly** from a temporary, the temporary persists for the lifetime of the reference. Only references that can bind to an rvalue qualify: `const std::string&`, `std::string&&` and `auto&&`; a plain `std::string&` is rejected with `non-const lvalue reference ... cannot bind to a temporary`. Directly includes a few forms the standard lists: a parenthesized temporary, a cast to a reference to the same object, a ternary or comma whose result is the temporary, and member access with `.` to a **data member** or base of a temporary, which extends the whole complete object. It does not include anything returned by a function: `const auto& items = parse(text).items();`, where `items()` returns a reference into the document, leaves `items` dangling because the document dies at the semicolon. The code example prints exactly that order.
code
cpp · 19 lines#include <cstdio>
#include <string>
#include <vector>
struct Document {
std::vector<std::string> values{"alpha"};
~Document() { std::puts("~Document"); }
const std::vector<std::string>& items() const { return values; }
};
Document parse(const char*) { return {}; }
int main() {
std::puts("1: const& bound to the returned Document");
const Document& doc = parse("{}"); // extended to the end of main
std::puts("2: const& bound to a data member of a temporary");
const auto& vals = parse("{}").values; // whole Document extended
std::puts("3: const& bound to what a getter returns");
const auto& items = parse("{}").items(); // Document destroyed at the ';'
std::puts("4: end of main body");
(void)doc; (void)vals; (void)items;
}go deeper
Know that a const reference initialized from a function's by-value result keeps that result alive for the reference's scope.
Explain that only direct binding extends, list const T&, T&& and auto&&, and show why a getter returning a reference into a temporary dangles while a data member access does not.
Review APIs for accessors that return references into short-lived objects, and use Clang's -Wdangling, GCC's -Wdangling-reference or lifetimebound annotations to catch them.
Decide whether a codebase allows reference-returning accessors on value types, weighing the copies avoided against a class of dangling bugs no type check can see.
## The rule The standard lists reference binding as one of the contexts in which a temporary is destroyed later than the end of its full-expression: "the temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference" — provided the reference was bound to it through one of a short list of expressions. The practical reading: - `const std::string& name = doc.name();` — `name()` returns a prvalue, which is **materialized** into a temporary when the reference binds, and the temporary lives until `name` goes out of scope. - `std::string&& name = doc.name();` and `auto&& name = doc.name();` — the same extension through an rvalue or forwarding reference. - `std::string& name = doc.name();` — ill-formed: a non-const lvalue reference cannot bind to a temporary. Clang says `non-const lvalue reference to type 'basic_string<...>' cannot bind to a temporary of type 'basic_string<...>'`. Extension is per reference and only for that reference's scope. Once `name` is gone, the temporary is destroyed, in the usual reverse order relative to the other locals. ## What "directly" covers The draft spells out which expressions keep the link between the reference and the temporary: 1. the temporary materialization itself, as in `const T& r = make();`; 2. a parenthesized expression of one of these forms; 3. subscripting an array temporary, as in `id<int[3]>{1, 2, 3}[i]`; 4. class member access with `.` naming a non-static **data member** of non-reference type, or a base class subobject — this extends the **complete object**, not just the member; 5. `.*` with a pointer to data member; 6. `const_cast`, `static_cast`, `dynamic_cast` or `reinterpret_cast` to a reference that still designates that object, without a user-defined conversion; 7. a glvalue conditional `?:` or comma expression whose result is one of these. Row 4 is the one interviewers like: `const auto& vals = parse(text).values;` keeps the entire `Document` alive for as long as `vals` exists. The draft adds a recursive note: if a temporary has a reference member initialized by another temporary, extension applies to that member's initializer too. Its example is `struct S { const int& m; };` with `const S& s = S{1};`, where both the `S` and the `int` temporaries live as long as `s`. The same chain of direct bindings is what makes `View v{load_name()};` safe in the subtleties below. ## Where the link breaks The list contains no function calls. A member function such as `items()` that returns `const std::vector<std::string>&` produces an lvalue the compiler cannot trace back to the temporary, so: - `const auto& vals = parse(text).values;` — member access, the document is extended; - `const auto& items = parse(text).items();` — getter returning a reference, the document dies at the semicolon and `items` dangles. The code example prints both orders on Apple clang 21: the getter case prints `~Document` before the next statement, the other two only at the end of `main`. The same trap catches `const auto& m = std::max(a_temp, b_temp);`. libc++ marks `std::max`'s parameters with `_LIBCPP_LIFETIMEBOUND`, so Clang warns `temporary bound to local reference ... will be destroyed at the end of the full-expression [-Wdangling]`. GCC documents `-Wdangling-reference`, enabled by `-Wextra`, for the same pattern. ## Two subtleties - **By-value getters are fine.** If `items()` returned `std::vector<std::string>` by value, `const auto& items = parse(text).items();` would extend the *returned vector*, which owns copies; the destroyed document no longer matters. - **Aggregates with reference members.** `struct View { const std::string& name; };` then `View v{load_name()};` extends the string, because aggregate brace initialization binds the member directly. `View v(load_name());` with C++20 parenthesized aggregate initialization does **not** extend it; Clang warned `temporary whose address is used as value of local variable ... will be destroyed at the end of the full-expression [-Wdangling]`. ## Why the rule exists Lifetime extension lets `const T&` parameters and locals accept values without copies, and lets code bind a name to a function's result without caring whether it is returned by value. It was never meant as a general "references keep objects alive" rule, and treating it as one is the source of nearly every dangling-reference interview question. A safe habit: bind a reference only to the **direct** result of a by-value call, and store anything else by value.
- Does binding a temporary to a const reference member of a class extend it?Not through a constructor. Binding a temporary to a reference member in a mem-initializer is ill-formed, and a temporary passed to a constructor's `const T&` parameter and stored in a member lives only until the end of the full-expression containing the constructor call. The exception is aggregate brace initialization of a local, such as `View v{load_name()};`, which binds the member directly and extends the temporary.
- Does auto&& extend a temporary the same way as const auto&?Yes. `auto&& r = make();` deduces an rvalue reference to the materialized temporary and extends it for `r`'s lifetime, and unlike `const auto&` it leaves the object modifiable. That is exactly how the range-based `for` statement holds its range expression: it is specified as `auto&& range = range-expression;`.
- Is the extended temporary copied into the reference's storage?No copy or move is involved. Since C++17 the prvalue is materialized directly into the temporary object, and extension only changes when that temporary is destroyed. The temporary is destroyed when the reference's lifetime ends, in reverse order relative to the other objects of the same storage duration.
Extension is like signing for a parcel yourself: if you take it straight from the courier, it is yours as long as you keep it. If someone else signs and hands you a note saying where it is, the parcel goes back when they leave.
- Any reference, including a non-const lvalue reference, can bind and extend a temporary.
- A getter returning const T& into a temporary object also extends that object.
- Binding a const reference to a temporary makes a hidden copy of it.
- Binding to a data member of a temporary extends only that member, not the whole object.
- Lifetime extension makes every stored reference to a temporary safe.