Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer
(Page 1 of 6 )
As you know, in programming C++, it is much better to return a reference to an object than it is to return that object by value. As we will see in this article, it is also much better to pass a function parameter by reference than it is to pass it by value. But there are exceptions to this, as Jun Nakamura explains.
You will find it a very good practice always to verify your references, sir.
[Martin Routh 1755-1854]
Finding the Closest Enemy
We have been looking at temporary objects and the effect they can have on the performance of an application. As an example I offered a function that can tell the AI of a game which enemy is located closest to the player from a list that was provided as a function argument.
Refer to the previous article for the initial definition of the following function:
Enemy FindClosest(list<Enemy> enemies, Player player);
The conclusion was that it is much better to return a reference to an object than it is to return that object by value. Likewise it is much better to pass a function parameter by reference than it is to pass it by value. We actually have to apply this rule to this function before we can return a reference to an enemy.
Next: To pass or not to pass by value >>
More C++ Articles
More By J. Nakamura