In C++, a JSON helper's Settings object stores a const std::string& member taken from a temporary; where does lifetime extension fail, and why?
answer
- parameters end at the semicolon
- returned references are never extended
- mem-initializer binding is rejected
- new-initializer and parenthesized aggregates
- C++26 makes returning one ill-formed
basics
~20 sExtension covers only a reference bound directly to a temporary. A temporary passed to a constructor's const reference parameter dies at the end of that statement, so a member bound from it dangles; returned references and mem-initializers are never extended.
solid answer
~40 s`Settings s(load_name());` passes the temporary string to `Settings(const std::string& n)`, and the standard says a temporary bound to a **reference parameter** persists only until the full-expression containing the call completes. Initializing the member `name(n)` binds to the parameter, not the temporary, so after the semicolon `s.name` dangles; Clang gave no warning, and AddressSanitizer reported stack-use-after-scope. The other non-extensions: binding a temporary to a reference member in a **mem-initializer** is ill-formed; a temporary bound to a reference in a **new-initializer** dies at the end of that full-expression; C++20 **parenthesized aggregate** initialization does not extend; and a **returned reference** is never extended: in C++23 `return std::string("tmp");` from a `const std::string&` function dangles, while C++26 makes it ill-formed. The fix is to store a `std::string` member, not a reference.
code
cpp · 11 lines#include <cstdio>
#include <string>
struct Settings {
const std::string& name; // reference member: does not own the string
explicit Settings(const std::string& n) : name(n) {}
};
std::string load_name() { return "config-name-long-enough-to-allocate"; }
int main() {
Settings s(load_name()); // the temporary std::string dies at this ';'
std::printf("%s\n", s.name.c_str()); // undefined behaviour: dangling reference
}go deeper
Know that a temporary passed to a function dies at the end of that statement, so storing a reference to it is a bug.
Explain why binding a member to a reference parameter is not lifetime extension, and list mem-initializers and returned references as cases the language rejects or does not extend.
Trace the lifetime at each binding step in a constructor, choose owning members or deleted rvalue overloads, and know what Clang, GCC and AddressSanitizer each catch.
Set a rule for reference members and reference-returning accessors in value types, and track C++26's ill-formed returned-reference rule as a toolchain upgrade benefit.
## Extension is narrow on purpose Lifetime extension happens only when a reference is bound **directly** to a temporary and the reference outlives the full-expression. Each case below breaks one of those two conditions, and the standard lists most of them by name as "exceptions to this lifetime rule". ## The cases that do not extend | Code | What the standard says | Result | |---|---|---| | `Settings s(load_name());` with a constructor `Settings(const std::string& n) : name(n)` | a temporary bound to a reference parameter persists until the full-expression containing the call completes | `s.name` dangles after the semicolon | | `Bad() : name(std::string("x")) {}` with `const std::string& name;` | a temporary expression bound to a reference member in a mem-initializer is ill-formed | compile error | | `View v(load_name());` (C++20 parenthesized aggregate init) | a temporary bound to a reference element of an aggregate initialized from a parenthesized list persists until the end of the full-expression | `v.name` dangles | | `new View{load_name()}` | a temporary bound to a reference in a new-initializer persists until the end of the full-expression | the heap object's member dangles | | `const std::string& pick() { return std::string("tmp"); }` | C++23: not extended, destroyed at the end of the return statement; C++26: ill-formed | dangling result or compile error | | `const auto& items = parse(text).items();` | a function's returned reference is not on the list of extending expressions | `items` dangles | ## The JSON helper case in detail A `Settings` type with a `const std::string& name` member looks cheap: no copy. The constructor takes `const std::string& n` and initializes `name(n)`. Follow the lifetime at each step: 1. `load_name()` returns a prvalue; binding the parameter `n` materializes it as a temporary. 2. That temporary is bound to a **function parameter**, so it lives until the end of the full-expression `Settings s(load_name());`. 3. The member `name` binds to `n`, an lvalue that already refers to the temporary, so the member's binding is not a binding to a temporary expression and extends nothing. 4. At the semicolon the string is destroyed; `s` still holds a reference to it. On Apple clang 21 this compiled with `-Wall -Wextra` and no warning, and AddressSanitizer reported **stack-use-after-scope** when `s.name` was read. The bug is invisible to the type system because the constructor is legal for an lvalue argument whose lifetime is long enough. ## What the compilers catch - The mem-initializer case is rejected outright. Clang: `reference member 'name' binds to a temporary object whose lifetime would be shorter than the lifetime of the constructed object`. - Returning a reference to a temporary: in C++23 mode Clang warns `returning reference to local temporary object [-Wreturn-stack-address]`; with `-std=c++2c` it is an **error**, matching C++26's rule (P2748R5) that a return statement binding a returned reference to a temporary expression is ill-formed. - Parenthesized aggregate initialization: Clang warned `temporary whose address is used as value of local variable ... will be destroyed at the end of the full-expression [-Wdangling]`. - Reference-returning accessors: Clang's `[[clang::lifetimebound]]` on the implicit object parameter makes `const auto& items = parse(text).items();` warn; GCC documents `-Wdangling-reference`, enabled by `-Wextra`, for a local reference bound to what a call returns when the call was given a temporary, member calls included. - The constructor-parameter case is the hardest: Clang gave no warning on it here, and a sanitizer or a review rule is what finds it. ## Fixes 1. **Own the data.** Make the member `std::string name;` and take the parameter by value, then `std::move` it in: one move for temporaries, one copy for lvalues. 2. **Delete the rvalue overload** if a non-owning reference member is truly required: `Settings(std::string&&) = delete;` rejects temporaries at compile time. 3. **Return by value** from accessors on objects that are commonly temporaries, or provide `const&`- and `&&`-qualified overloads so the rvalue version returns by value. 4. **Annotate** reference-returning functions with `[[clang::lifetimebound]]` where Clang is in the build. ## The point to make A strong answer explains that extension is decided by the **syntax at the binding site**, not by where the reference ends up, walks the constructor-parameter case step by step, and knows that C++26 turns the returned-reference case from a silent dangle into a compile error.
- How can a class keep a reference member but refuse temporaries at compile time?Add a deleted overload for rvalues, `Settings(std::string&&) = delete;` (or `const std::string&&`), beside `Settings(const std::string&)`. A temporary argument then prefers the rvalue overload, and Clang rejects the call with `call to deleted constructor of 'Settings'`. Callers must pass an lvalue whose lifetime they control, which documents the borrowing contract in the type.
- Why does `View v{load_name()};` extend the string while `View v(load_name());` does not?Brace aggregate initialization binds the reference member directly to the temporary inside the declaration of `v`, which the standard treats as a reference binding that persists for the reference's lifetime. C++20's parenthesized aggregate initialization was specified with an explicit exception: a temporary bound to a reference element there lives only until the end of the full-expression.
- Storing a const reference parameter in a member keeps the caller's temporary alive.
- Returning a const reference to a temporary is safe because const references extend lifetimes.
- If the code compiles without warnings, no reference member can dangle.
- new View{load_name()} extends the string for as long as the heap object lives.
- Parenthesized and braced aggregate initialization always have the same lifetime rules.
Assumes C++23; C++26 (P2748R5) makes binding a returned reference to a temporary ill-formed, and parenthesized aggregate initialization exists since C++20.