I thought references only extend the lifetime of temporaries to the lifetime of the reference itself, but the output of the following snippet seems contradictory:
#include <iostream>
struct X{ ~X(){ std::cout << "Goodbye, cruel world!\n"; } };
X const& f(X const& x = X()){
std::cout << "Inside f()\n";
return x;
}
void g(X const& x){
std::cout << "Inside g()\n";
}
int main(){
g(f());
}
Live example. Output:
Inside f()
Inside g()
Goodbye, cruel world!
So it seems the temporary is destroyed after g()
is called... what gives?
The standard handles this in a special case in
§12.2 [class.temporary]
:The standard also has a handy note on full-expressions and the evaluation of their subexpressions with regards to default parameters in
§1.9 [intro.execution] p11
:Interesting, +1. (I do not mean to compete with your nice self answer here). Just a side note for anyone interested. If you want a similar effect but allowing non-const you could use move semantics:
gives