Prevents generation of copy constructor and copy assignment operator in derived classes. More...
Prevents generation of copy constructor and copy assignment operator in derived classes.
To prevent generation of copy constructor and copy assignment operator, inherit privately from the NonCopyable class.
Instances of polymorphic classes are not meant to be copied. The C++ standards generate a default copy constructor and copy assignment function if these functions have not been defined in the class.
Consider the following example:
There is a subtle bug in this code, the function get_connection returns a reference to a Connection which is captured by value instead of reference.
get_connection returns a reference to serial_connection it is copied into the local variable connection. The vtable and others members defined in Connection are copied, but members defined in SerialConnection are left apart. This can cause severe crashes or bugs if the virtual functions captured use members not present in the base declaration.
To solve that problem, the copy constructor and assignment operator have to be defined as deleted:
Although manually defining deleted copy constructor and assignment functions works, it is not ideal. These declarations are usually easy to forget, not immediately visible, and may be obscure to uninformed programmers.
Using the NonCopyable class reduces the boilerplate required and expresses the intent because class inheritance appears right after the class name declaration.
Using a template type prevents cases where the empty base optimization cannot be applied and therefore ensures that the cost of the NonCopyable semantic sugar is null.
As an example, the empty base optimization is prohibited if one of the empty base classes is also a base type of the first nonstatic data member:
The solution to that problem is to templatize the empty class to make it unique to the type it is applied to:
|T||The type that should be made noncopyable.|
Definition at line 162 of file NonCopyable.h.