Consider
struct A {
~A() {std::cout << "A's dtor called\n";}
};
A f1(const A& a)
{
return a;
}
int main()
{
{
const A& r = f1(A());
std::cout << "XXX\n";
}
std::cout << "YYY\n";
}
Output:
A's dtor called
XXX
A's dtor called
YYY
Now let
const A& f2(const A& a)
{
return a;
}
and consider the output of the same main-function except that f1 is replaced with f2:
Output this time:
A's dtor called
XXX
YYY
Why is that? Shouldn't - in the second case - the temporary A() that is passed through f2 "live" until the entire expression const A& r = f2(A()) has been executed? In that case I'd expect that the lifetime of the temporary should be extended until r dies (as in the first case), but it dies already before cout << "XXX" gets executed. Or is the initialization of r not part of the expression into which the evaluation of f2 is involved, so that A() is already dead before it can be bound to r?
Aucun commentaire:
Enregistrer un commentaire