| High Integrity CPP Guideline 17.3 | Make copying efficient for objects in containers. |
| Justification |
It is important to be aware that STL containers use copy operations and to implement these operations as efficiently as possibly. When an object is added to a container it is copied and the copy is stored inside the container; for objects of class type this copy is made by the class copy constructor. For some container types, including vector, objects may be moved inside the container; this move will use the class copy assignment operator.
class MyClass
{
public:
MyClass();
MyClass( MyClass const& rhs ); // copy ctor
MyClass& operator=( const MyClass& rhs ); // copy assignment
};
void foo( const MyClass& obj, const MyClass& anotherObj )
{
std::vector< MyClass > vec;
// Call to push_back will call the copy constructor.
//
vec.push_back( obj );
// Call to insert will call the copy assigment operator for
// each object stored after the insert iterator.
//
vec.insert( vec.begin(), anotherObj );
}
|
| See also |
Guideline 17.4 |
| Reference |
Effective STL Item 3; |