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:
Enemy const& FindClosest(list<Enemy> const &enemies,
Player const &player) {
assert (!enemies.empty());
list<Enemy>::const_iterator closest;
float min_sqdistance = FLT_MAX;
list<Enemy>::const_iterator nmeIt;
for (nmeIt=enemies.begin(); nmeIt!=enemies.end(); nmeIt++)
{
Vector3 nme2ply=player.GetPos() – nmeIt->GetPos();
float sqdist=nme2ply.squaredLength();
if (sqdist < min_sqdistance)
{
closest=nmeIt;
min_sqdistance=sqdist;
}
}
return *closest;
}
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.
Next: Call optimization >>
More C++ Articles
More By J. Nakamura