Temporary Variables: Temporaries Are Not Necessarily Evil
In earlier articles, we learned about the problems the passing of objects by value can cause in C++. Returning objects by value, on the other hand, is not necessarily evil. Jun Nakamura explains the finer points.
Temporary Variables: Temporaries Are Not Necessarily Evil - Binding a reference to a temporary object (Page 2 of 4 )
It is clear that the lifetime of a temporary object is exactly that… temporary. For the same reason, it is not possible to return a pointer or reference to a local object -- because its lifetime is temporary. So beware and stay clear of the following type of code:
party crasher called! partyCrasher created. partyCrasher destroyed. ¿³? shouts:’Crash the party!’ Done!
Hopefully your compiler has generated a warning about returning the address of a local variable or temporary in this function. It is wise to heed your compiler’s warnings, as this shows that only a fool would ignore them.
The output makes it clear that the partyCrasher was destroyed before it was used. This is all as we expected.
Here is what happens when we try anotherPartyCrasher function:
another party crasher called! anotherPartyCrasher created. AnotherPartyCrasher shouts:’Crash the party!’ Done! AnotherPartyCrasher destroyed.
Lo and behold! Apparently the temporary object is only destroyed when it leaves the scope of the function where it was created for an expression that needed it. This behavior is actually guaranteed by the C++ Standard, so it is fine to bind a reference to a temporary object as long as you only use it in the same scope it was created in.