What is the rationale for extending the lifetime of temporaries?
c++, language-design
Solution
The simple answer is that you need to be able to bind a temporary with a const reference, not having that feature would require a good amount of code duplication, with functions taking `const&` for lvalue or value arguments or by-value for rvalue arguments. Once you need that the language needs to define some semantics that will guarantee the lifetime of the temporary is at least as long as that of the reference.
Once you accept that a reference can bind to an rvalue in one context, just for consistency you may want to extend the rule to allow the same binding in other contexts, and the semantics are really the same. The temporary lifetime is extended until the reference goes away (be it a function parameter, or a local variable).
The alternative would be rules that allow binding in some contexts (function call) but not all (local reference) or rules that allow both and always create a dangling reference in the latter case.
Removed the quote from the answer, left here so that comments would still make sense:
If you look at the wording in the standard there are some hints as of this intended usage:
12.2/5 [middle of the paragraph] [...] A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. [...]
Problem
In C++, the lifetime of a temporary value can be extended by binding it to a reference: ``` Foo make_foo(); { Foo const & r1 = make_foo(); Foo && r2 = make_foo(); // ... } // both objects are destroyed here ``` Why is this allowed? What problem does this solve? I couldn't find an explanation for this in Design and Evolution (e.g. 6.3.2: Lifetime of Temporaries). Nor could I find any previous questions about this (this one came closest). This feature is somewhat unintuitive and has subtle failure modes. For example: ``` Foo const & id(Foo const & x) { return x; } // looks like a fine function... Foo const & r3 = id(make_foo()); // ... but causes a terrible error! ``` Why is something that can be so easily and silently abused part of the language? Update: the point may be subtle enough to warrant some clarification: I do not dispute the use of the rule that "references bind to temporaries". That is all fine and well, and allows us to use implicit conversions when binding to references. What I am asking about is why the lifetime of the temporary is affected. To play the devil's advocate, I could claim that the existing rules of "lifetime until end of full expression" already cover the common use cases of calling functions with temporary arguments.