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 - Death by Returned const Reference (Page 3 of 4 )
My previous article ended with a function declaration that demonstrated the possibility of crafting a reference to a temporary object in a rather cunning way. Let's give that function a body and another try. While it may be safe to bind a reference to a temporary object, you cannot do so blindly.
Base const& AnotherCallByReference(Base const &obj) { return obj; }
Reusing the Base and Empty classes from the previous article, we gain more insight into the lifetime of temporary objects.
If you’ve read the previous article, you now know that it is possible for an object to be sliced when a function accepts parameters passed by value or by const reference. Here it is possible to pass an Empty object into the AnotherCallByReference function, because the Base class has a conversion constructor that accepts Base objects.
NoBase nobase_obj; Base const& crashbase=AnotherCallByReference(nobase_obj); Crashbase.foo(); (void)printf(“Done!\n”);
Now you see that the const reference returned, does not necessarily refer to the object originally passed in to the function!
NoBase object created Base created from NoBaseobject Base destroyed Base::foo() called
The caller received a const reference to a temporary object, and when it tried to call function foo() on it, the temporary object had already been destroyed!