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!
"; } };
X const& f(X const& x = X()){
std::cout << "Inside f()
";
return x;
}
void g(X const& x){
std::cout << "Inside g()
";
}
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…