|Synopsis:||A class that manages resources shall declare a copy constructor, a copy assignment operator, and a destructor|
|Category:||Object Oriented Programming|
When a copy constructor and a assignment operator do not exist, they are automatically generated by the compiler. This may easily result in runtime errors when an object is copied while this was not intended by the class implementation.
If instances of a class are not intended to be copied, the copy constructor and assignment operator must be declared private and no implementation must be provided. If the copy constructor or assignment operator is used by something else than the class itself or a friend of the class, the compiler issues an error because it does not find a declaration. If the class itself or a friend of the class uses the copy constructor or assignment operator the linker issues an error because it cannot find an implementation.
The above even applies to abstract base classes, that is classes with one or more pure virtual methods. A derived class might want to use the copy constructor or assignment operator of the abstract base class. If the abstract base class is not intended to be copied it must provide a private copy constructor.
If instances of a class are intended to be copied and that class has data-members that refer to resources (e.g. pointer to memory) the class must declare and define a copy constructor and an assignment operator.
The copy constructor and assignment operator are declared and defined to make sure that it is not the reference to the resource that is being copied but the data referenced. See also [Meyers] item 11.
|Ellemtel Rule 26, adapted.|
|ISC++ Rec. 5.11|