| High Integrity CPP Guideline 17.4 | Where copying is expensive use containers of pointers or smart pointers. |
| Justification |
Pointers are small and have builtin operators for copying values. Because of this containers of pointers are efficient for insertion, sorting and other operations. If containers of pointers are used then it is the responsibility of the programmer to manage the lifetime of the objects. This can be done with a reference counting smart pointer class.
class BigClassWithLotsOfData {};
void badVectorUsage( std::vector< BigClassWithLotsOfData >& vec )
{
BigClassWithLotsOfData newObj;
vec.push_back( newObj ); // calls expensive copy constructor!
}
void goodVectorUsage( std::vector< BigClassWithLotsOfData* >& vec )
{
// This only copies a pointer so insertions are cheap.
//
BigClassWithLotsOfData* pNewObj = new BigClassWithLotsOfData;
vec.push_back( pNewObj );
}
|
| See also |
| Reference |
Effective STL Item 3; |