* Victor Bazarov:
struct A { int i; A(int i) : i(i) {}; operator int() { return i; }};
A const& f()
{
return 2;
}
int main()
{
int i = f();
}
is it legal or does the temporary get destroyed at the 'f's closing brace?
Answering my own original innocent question, now escalated into a full-blown
debate: it's the latter (as would also be the case with just using 'int').
§12.2/5 "A temporary bound to the returned value in a function return
statement (6.6.3) persists until the function exits".
If this was not the case, then gross inefficiencies would have to be
introduced to allocate memory for the result of a function for the
general case. With a reference result the referred object can be
any size whatsoever. Which means that the calling code cannot pre-
allocate space on the stack.
But of course we can wonder _why_ the standard requires near certain UB
(only if you don't use the result in any way can you avoid UB) instead
of simply disallowing this thing. Well, it may be the case that it one
return path the function returns a valid reference, while in another,
just a temporary to satisfy that warning-addicted compiler. Or it may
be the case that the programmer is engaging in Unholy Practices to obtain
the stack-pointer.
Although I would have preferred that the standard disallowed this...
Cheers,
- Alf