Synopsis: | A class that manages resources shall declare a copy constructor, a copy assignment operator, and a destructor |
Language: | C++ |
Severity Level: | 2 |
Category: | Object Oriented Programming |
Description: |
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 as deleted functions: class X { X& operator=(const X&) = delete; // Disallow copying X(const X&) = delete; }; 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.
|