Item 6. Temporary Objects
Difficulty: 5
Unnecessary and/or
temporary objects are frequent culprits that can throw all your
hard work—and your program's performance—right out the window. How
can you spot them and avoid them?
("Temporary objects?"
you might be wondering. "That's more of an optimization thing.
What's that got to do with generic programming and the standard
library?" Bear with me; the reason will become clear in the
following Item.)
You are doing a code review. A programmer has
written the following function, which uses unnecessary temporary
objects in at least three places. How many can you identify, and
how should the programmer fix them?
string FindAddr( list<Employee> emps, string name )
{
for( list<Employee>::iterator i = emps.begin();
i != emps.end();
i++ )
{
if( *i == name )
{
return i->addr;
}
}
return "";
}
Do not change the operational semantics of this
function, even though they could be improved.
|