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?
answer
- range-for is auto&& range = ...
- only the outermost result is bound
- the Document dies before the body
- C++23 extends every temporary there
- C++20 init-statement as the fix
basics
~20 sA 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.
solid answer
~50 sThe standard defines `for (decl : range-init) body` as `{ auto&& range = range-init; auto begin = ...; auto end = ...; for (...) { decl = *begin; body } }`. With `items()` returning `const std::vector<std::string>&` into the document, `range` binds to a reference returned by a function, which never extends anything, so up to C++20 the temporary `Document` from `parse(text)` dies at the end of that hidden declaration, before the first iteration. The loop then walks a destroyed vector: undefined behaviour. On Apple clang 21 in C++20 mode it printed `~Document` and no items, and AddressSanitizer reported stack-use-after-scope. C++23 (P2718R0) changed the rule: a temporary created in the range initializer that would die at the end of that full-expression persists for the lifetime of `range`, so the same code prints both items. For C++17 and C++20 code, name the object first, or use C++20's init-statement `for (auto doc = parse(text); const auto& x : doc.items())`.
code
cpp · 17 lines#include <cstdio>
#include <string>
#include <vector>
struct Document {
std::vector<std::string> values;
explicit Document(std::vector<std::string> v) : values(std::move(v)) {}
~Document() { std::puts("~Document"); }
const std::vector<std::string>& items() const { return values; } // reference into *this
};
Document parse(const char*) {
return Document{{"alpha-long-enough-to-allocate", "beta-long-enough-to-allocate"}};
}
int main() {
for (const auto& x : parse("[...]").items())
std::printf("item %s\n", x.c_str());
std::puts("after loop");
}go deeper
Know that looping over something obtained from a temporary object can read destroyed data, and that naming the object first avoids it.
Explain the auto&& range rewrite and why a getter returning a reference into a temporary breaks extension while a by-value getter does not.
Diagnose the pre-C++23 dangling loop, fix it with a named object or the C++20 init-statement, and explain P2718R0 with its caveats on parameters and delayed destructors.
Weigh relying on C++23's rule against keeping code safe under older standards, especially in headers compiled by consumers on different -std settings.
## How the range-based for is defined The range-based `for` statement is specified as a rewrite. `for (const auto& x : parse(text).items()) body` is equivalent to: ```cpp { auto&& range = parse(text).items(); auto begin = range.begin(); auto end = range.end(); for (; begin != end; ++begin) { const auto& x = *begin; // loop body } } ``` So the loop's correctness depends on one declaration, `auto&& range = range-init;`, and on the ordinary lifetime-extension rules applied to it. ## Why it dangles before C++23 Follow each object: 1. `parse(text)` returns a `Document` prvalue; calling `items()` on it materializes a **temporary** `Document`. 2. `items()` returns `const std::vector<std::string>&` that refers into that temporary. A reference returned by a function is not one of the expressions that extend a temporary. 3. `range` binds to that returned reference. Nothing ties it to the `Document`, so up to C++20 the `Document` is destroyed at the end of the full-expression, which is the hidden declaration of `range`. 4. `begin` and `end` are then computed from a vector inside a destroyed object, and the loop body reads freed or out-of-scope memory. On Apple clang 21 with `-std=c++20`, the program printed `~Document` immediately, then `after loop`, with no items at all; AddressSanitizer reported **stack-use-after-scope**. Both are just observed outcomes of undefined behaviour. ## Cases that were always fine - `for (const auto& x : parse(text))` — the range is the temporary itself, bound directly to `range` and extended. - `for (const auto& x : parse(text).values)` — member access to a data member extends the whole `Document`. - `for (const auto& x : parse(text).items_copy())` where the getter returns `std::vector<std::string>` **by value** — the returned vector is the temporary bound to `range`, and it owns its elements. The trap is specifically a function that returns a reference, pointer or view into a temporary. Reviewers can spot it mechanically: look at the range expression of every range-based `for`, find the last function call in it, and check whether that call's result refers into an object created earlier in the same expression. If it does, the loop is only correct under C++23 or later. ## What C++23 changed C++23 adopted P2718R0, the wording for P2644R1, "Fix for Range-based for Loop". The draft now names a fourth context in which temporaries live longer: a temporary created in the for-range-initializer that "would otherwise be destroyed at the end of the for-range-initializer full-expression" persists for the lifetime of the reference initialized by it. Every temporary in that expression, including the `Document`, now lives until the loop ends. The same program built with `-std=c++23` printed both items and then `~Document`. Two caveats keep this from being a universal fix: - It only covers **temporaries**. If a function takes its argument by value and returns a reference to that parameter, the parameter is not a temporary, and the draft's own example `for (auto e : f2(g())) {}` remains undefined behaviour. - Destructors now run later. The compatibility annex shows a `std::lock_guard` temporary in the range expression that used to release its lock before the body and now holds it for the whole loop, deadlocking code that locks the same mutex inside. GCC 16.2 documents `-frange-for-ext-temps` to enable the extension in modes before C++23; with `-std=c++23` and later it is the default. ## Fixes for C++17 and C++20 1. **Name the object.** `const auto doc = parse(text); for (const auto& x : doc.items()) ...` — the document is an ordinary local. 2. **Use the C++20 init-statement.** `for (auto doc = parse(text); const auto& x : doc.items())` keeps `doc` alive for exactly the loop. Clang accepts it in C++17 mode only as an extension, with a `-Wc++20-extensions` warning. 3. **Change the API.** Give `items()` an `&&`-qualified overload that returns by value, so a call on a temporary yields an owning result. ## How to answer State the rewrite with `auto&& range`, show that the returned reference breaks extension, name the C++23 change and its paper, and give the init-statement fix for older standards, plus the one caveat that C++23 now delays destructors such as a lock guard's.
- Does C++23 make `for (auto& x : f(g()))` safe when f takes its argument by value and returns a reference to it?No. C++23 extends temporaries created in the range initializer, but a by-value function parameter is not a temporary: it is destroyed when the call ends, at the latest at the end of the full-expression. The returned reference still dangles, and the draft keeps this exact case as an example of undefined behaviour.
- How can the C++23 rule change the behaviour of correct C++20 code?Destructors of temporaries in the range initializer now run after the loop instead of before it. The compatibility annex shows a `std::lock_guard` temporary created in the range expression: in C++20 it released the mutex before the body, so locking the same mutex in the body worked; in C++23 the lock is held for the whole loop and the body deadlocks.
- The range expression of a range-based for is always kept alive until the loop ends, in every standard.
- If items() returned by value the loop would dangle too.
- C++23 also fixes functions that return references to their own by-value parameters.
- Binding the loop variable with auto&& instead of const auto& fixes the dangling.
- The C++23 change cannot alter the behaviour of any program that was correct before.
Assumes C++23, where P2718R0 extends temporaries in the range initializer to the end of the loop; C++17 and C++20 code still has the dangling behaviour.