Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer
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.
Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer - Const-Correctness (Page 3 of 6 )
When we pass a function argument by reference, the function is allowed to manipulate and make changes to the object being referenced. Some would even argue that for this very reason it is safer to pass function arguments by value when you want to make sure the function doesn’t make any alterations to them. I prefer to use constant references instead.
By passing a const reference to a function, you forbid the function to make any changes to the object via that reference. Now we can make our first alteration to the FindClosest function:
This alteration saves the need to construct an Enemy object local to the function body, and also the need to construct a temporary object to carry the result over to the caller.