Declare unwanted member functions private without implementations to disallow functionality automatically provided by compilers.
If we want to prevent functions such as copy constructor being generated in order to maintain the object uniqueness, explicitly declare the copy constructor and the copy assignment operator private, so that the client of the class will not be able to copy the object.
To make it foolproof, declare member functions private and deliberately not implemente them so that member and friend functions will not be able to copy the object, either.
Another possible solution to prevent copying is to inherit from a well-designed base class such as this:
|
|
To inherit from the base class, simply:
|
|
This will be the same effect as the following design:
|
|
There are some subtleties about the implementation and use of Uncopyable
:
- inheritance from
Uncopyable
needn’t be public (item 32 and 39) Uncopyable
destructor needn’t be virtual (item 7: the base class is not designed to be used polymorphically)- it’s eligible for the empty bass class optimization described in item 39, but use of this technique could lead to multiple inheritance (item 40), which will sometimes in turn disable the empty base class optimization (item 39)
- Boost (item 55) provides a similar class named
noncopyable