C++26: Disallow Binding a Returned Reference to a Temporary -- Sandor Dargo
This change in C++26 tightens the rules around returning references to temporaries — and that’s a good thing. It turns dangerous, bug-prone code into immediate compilation errors, making code safer and easier to reason about. It also reflects a broader trend in modern C++: giving programmers stronger guarantees and better diagnostics, even at the cost of breaking some old patterns.
C++26: Disallow Binding a Returned Reference to a Temporary
by Sandor Dargo
From the article:
In short, thanks to P2748R5 by Brian Bi, it’s no longer possible to return a reference that binds to a temporary expression, and that’s just lovely.
What exactly is changing?
Often, a proposal modifies a lot of wording, and it’s not practical to start by reading through it all. But in this case, the changes are small and easy to digest, so let’s dive in.
This line is being removed:
“The lifetime of a temporary bound to the returned value in a function return statement (8.7.4) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.”
And this line is being added (excluding the examples we’ll discuss in a moment):
“In a function whose return type is a reference, other than an invented function for
std::is_convertible
([meta.rel]), a return statement that binds the returned reference to a temporary expression ([class.temporary]) is ill-formed.”There are two interesting shifts here:
- The language becomes more specific. It doesn’t merely mention “temporaries” but refers directly to references binding to temporary expressions, with certain exceptions.
- The effect isn’t just that lifetime extension doesn’t happen, it’s now a compilation error. The code is ill-formed.