Temporary Variables: Procrastination is the Thief of Time - More than just a call
(Page 3 of 6 )
Presume you are working on the AI for a video game where there are multiple enemies on the screen that have to attack the player in an intelligent way. The enemies are stored in a list, and we have to create a function that can determine which enemy is closest to the player.
Here is a first (naďve) attempt:
Enemy FindClosest(list<Enemy> enemies, Player player)
{
assert (!enemies.empty());
Enemy closest;
float min_sqdistance = FLT_MAX;
list<Enemy>::iterator nmeIt;
for (nmIt=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;
}
Can you spot all of the temporary objects used in this function? Before you point out that closest, min_sqdistance, nmeIt, nme2ply, and sqdist are all temporary objects, be aware that a compiler doesn’t see them this way. For a compiler these are variables that are local to a function and a ‘for’ loop, therefore they are not temporary at all. Note that they also fit the definition of an lvalue.
Temporary objects do not appear in your code, but are created by the compiler behind the scenes. This is why they are also called unnamed objects (or rvalues). There are two reasons why a compiler might have to do this:
- Because a function returns an object.
- Because an implicit conversion must be applied to make a function call succeed.
Next: To return or not to return an object >>
More C++ Articles
More By J. Nakamura