skip to content

Temporaries and Extension

A temporary dies at the end of its full expression unless a const reference extends it, and the rule has holes. Interviewers show a dangling string_view or a range-for over a temporary.

on this pageshow

explore

questions

4

In C++, when is a temporary object destroyed, such as the std::string a function returns inside a larger expression?

level: juniorimportance: must knowfreq 55%

answer

  1. not at the end of the block
  2. the whole statement, not the call
  3. usually the semicolon
  4. pointers into it die with it

basics

~20 s

A temporary is destroyed as the last step of evaluating the full-expression that created it, usually at the semicolon. So show(doc.name().c_str()) is safe, but keeping doc.name().c_str() in a pointer and using it later reads a destroyed string.

solid answer

~40 s

A temporary is an object the program never names: the `std::string` returned by value from `doc.name()`, a converted argument, `std::string("x")`. The standard destroys it as the **last step of evaluating the full-expression** that lexically contains the point where it was created, even if that evaluation ends by throwing. A full-expression is roughly the outermost expression: a whole expression statement, a variable's initializer, an `if` condition. So `show(doc.name().c_str())` is safe, because the string outlives the call to `show`. `const char* p = doc.name().c_str();` is not: the string dies at that semicolon, and using `p` afterwards is undefined behaviour. Clang warns with `-Wdangling-gsl` and AddressSanitizer reported a heap-use-after-free. The main exception is binding the temporary directly to a `const T&` or `T&&` local, which extends it.

code

cpp · 12 lines
cpp
#include <cstdio>
#include <string>
struct Document {
  std::string name() const { return "config-name-long-enough-to-allocate"; }
};
void show(const char* s) { std::printf("show: %s\n", s); }
int main() {
  Document doc;
  show(doc.name().c_str());                // OK: the string lives until the ';'
  const char* p = doc.name().c_str();      // the string dies at this ';'
  show(p);                                 // undefined behaviour: p dangles
}

go deeper

for a junior

Recall that a temporary dies at the end of the full statement that created it, and that pointers or iterators into it must not be kept.

for a middle

Explain what a full-expression is, why a temporary passed as an argument outlives the call, and how direct const reference binding extends a temporary.

for a senior

Spot dangling pointers into temporaries in review, name the tools that flag them, and know the standard's exceptions such as the C++23 range-for change.

for a principal

Set API conventions that make temporaries harmless, such as returning by value and avoiding accessors that hand out pointers into short-lived results.

## What counts as a temporary A **temporary object** is one the program creates without naming it. Since C++17 the standard describes most of them as the result of **temporary materialization**: a prvalue such as a function's by-value return or `std::string("x")` is not an object until something needs one, and it becomes a temporary when, for example, a member function is called on it or a reference binds to it. Typical sources: - a function that returns a class by value, as in `doc.name()`; - an explicit construction such as `std::string("tmp")` or `Point{1, 2}` used inside an expression; - an implicit conversion, such as a string literal turned into a `std::string` to match a `const std::string&` parameter. ## The full-expression rule The standard says temporaries are destroyed "as the last step in evaluating the full-expression that (lexically) contains the point where they were created", and that this holds even when the evaluation ends by throwing an exception. A **full-expression** is an expression that is not part of a bigger one: the whole expression of an expression statement, the initializer of a declared variable, the condition of an `if` or `while`, a member initializer in a constructor. Inner function calls, operands and arguments are only subexpressions, so a temporary created deep inside them survives until the outermost expression finishes. Within one full-expression, temporaries whose lifetime is not extended are destroyed in **reverse order** of their initialization. ## Safe and unsafe uses | Code | Verdict | Why | |---|---|---| | `show(doc.name().c_str());` | safe | the string lives until `show` returns and the statement ends | | `auto len = doc.name().size();` | safe | the value is copied out before the string dies | | `const char* p = doc.name().c_str();` then `show(p);` | undefined behaviour | the string died at the first semicolon | | `auto it = doc.name().begin();` then `*it` | undefined behaviour | an iterator into a destroyed string | | `const std::string& r = doc.name();` | safe | binding directly to a `const` reference extends the temporary | The code example runs the first and third rows. On Apple clang 21, Clang flagged the third at compile time with `object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]`, and AddressSanitizer reported a **heap-use-after-free** in `show`. Without the sanitizer such a read often prints the old text, which is exactly why it survives testing. ## How to keep the value 1. **Use it inside the same full-expression**, as in `show(doc.name().c_str())`. 2. **Copy it into a named object**: `std::string name = doc.name();` then work with `name.c_str()`. Since C++17 the copy is elided, so this costs nothing extra. 3. **Bind it directly to a `const T&` or `T&&` local**: the temporary's lifetime is extended to that reference's. This is the subject of lifetime extension, and it has holes worth learning separately. ## Exceptions to the rule The standard lists a handful of contexts where a temporary is destroyed at a different point than the end of its full-expression: - when a reference binds to it directly, the temporary lives as long as the reference; - since C++23, temporaries created in the range expression of a range-based `for` live until the loop ends; - default arguments used while constructing each array element are destroyed before the next element is built, and the same holds when a whole array is copied element by element. Everything else follows the semicolon rule, and that covers almost every case met in everyday code. One consequence surprises people who test with small strings: a short `std::string` usually keeps its characters inside the object itself (a small-string optimization that libc++, libstdc++ and the MSVC STL each implement differently), so a dangling `c_str()` pointer may point into a dead stack slot rather than freed heap memory. The behaviour is undefined either way, but which sanitizer report you get, or whether you get one, depends on the length of the text. ## What interviewers listen for A good answer names the **full-expression**, not "the end of the line" or "the end of the scope", and immediately gives the dangling-pointer example with `c_str()`. A stronger one mentions that the destruction happens even when an exception escapes, and that `const` reference binding is the deliberate exception rather than a general rule that references keep things alive.

  • Is a temporary passed to a function by const reference still alive inside that function?
    Yes. A temporary bound to a reference parameter lives until the full-expression containing the call completes, so it outlives the whole call. The danger is only in what the function does with the reference: if it stores the address somewhere that outlives the statement, such as a member of a longer-lived object, that stored reference dangles at the semicolon.
  • In `a = f(x) + g(y);`, which temporaries exist and when are they destroyed?
    The results of `f(x)` and `g(y)` are temporaries if they are class types, and so is the result of `operator+`. All are destroyed at the end of the full-expression, after the assignment completes, in reverse order of their initialization. None of them survives to the next statement unless a reference bound directly to one extends it.

  • A temporary lives until the end of the enclosing block, like a local variable.
  • A temporary is destroyed as soon as the function call that produced it returns.
  • Calling c_str() on a returned string gives a pointer that stays valid while the program runs.
  • If the dangling read prints the right text, the code is correct.
  • Any reference to a temporary keeps it alive as long as the reference exists.
open as a page

In C++, why is `const std::string& name = doc.name();` safe when name() returns by value, and which references extend a temporary?

level: middleimportance: must knowfreq 62%

basics

~20 s

Binding 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.

open as a page

In C++, why does `for (const auto& x : parse(text).items())` read destroyed data before C++23 when items() returns a reference, and what changed?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A range-based for binds its range expression to a hidden auto&& reference, which before C++23 extended only the final result, not the temporary Document that items() referred into. C++23 keeps every temporary in the range expression alive until the loop ends.

open as a page

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?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Extension 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.

open as a page