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 (Page 1 of 4 )
A thing may look specious in theory and yet be ruinous in practice;
A thing may look evil in theory, and yet be in practice excellent.
[Edmund Burke 1729-1797]
Finding the Closest Enemy
In the first article I made my first attempt to write a function that could determine which enemy is located closest to the player for a hypothetical video game. That first attempt gave us the following function declaration:
Enemy FindClosest(list<Enemy> enemies, Player player);
Of course there was a lot of room for improvement, since these articles serve to make a point about temporary objects. References are much more efficient in use than objects passed by value (as long as you remain aware that a const reference can cause the compiler to create a temporary object when a function call can be completed by using a conversion constructor)… thus we ended with the following declaration:
Enemy& FindClosest(list<Enemy> &enemies, Player const &player);
We now know what problems the passing of objects by value may bring, but returning objects by value is not necessarily evil. If we forced ourselves to use references all the time, we would miss out on some of the nicer features of the C++ language. On top of that we’ve seen that it is dangerous to return const references!
Another optimization could be found in the way the returned reference was handled. Returning a reference is useless when it is used to create a copy of the closest enemy regardless:
Enemy closest=FindClosest (enemies, player);
This will use an enemy object (stored in the enemies list) directly because we use the returned reference directly:
Enemy &closest=FindClosest (enemies, player);
What will happen in the last statement when FindClosest returns an object by value? This means that we are binding a reference to a temporary object. Is this safe?