Temporary objects are destroyed at the end of the full expression they're part of.
A full expression is an expression that isn't a sub-expression of some other expression. Usually this means it ends at the ;
(or )
for if
, while
, switch
etc.) denoting the end of the statement. In your example, it's the end of the function call.
Note that you can extend the lifetime of temporaries by binding them to a const
reference. Doing so extends their lifetime to the reference's lifetime:
MyClass getMyClass();
{
const MyClass& r = getMyClass(); // full expression ends here
...
} // object returned by getMyClass() is destroyed here
If you don't plan to change the returned object, then this is a nice trick to save a copy constructor call (compared to MyClass obj = getMyClass();
), in case return value optimization was not being applied. Unfortunately it isn't very well known. (I suppose C++11's move semantics will render it less useful, though.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…