In
template <typename T>
T const & foo(T const & dflt)
{ return /* ... */ ? /* ... */ : dflt; }
int x = foo(5);
Does the reference to temporary “survive” until it’s assigned to x?
(I know it survives the duration of the foo() call, but the assignment makes me hesitate)
The code in question has some legitimate uses for relying on const references here, i.e. I would need two separate functions
T const & foo_cr(T const & dflt);
T const & foo_v(T dflt);
which I want to avoid (just relying on different signatures wiht the same name seems a bit risky to me.)
Generally, yes. If
fooreturnsdflt, that reference (to a temporary 5) is valid until the end of the full-expression it was created in, that means, until after the initialization.C++03, 12.2/3:
More comes in 12.2/4 and 12.2/5, especially the exceptions of this rule.
I can’t see what happens when it returns the
...you left out, but I guess you weren’t asking about this.