π 2020-Mar-19 ⬩ βοΈ Ashwin Nanjappa ⬩ π·οΈ cpp ⬩ π Archive
There are situations when you would like to disable the default copy constructor and/or default copy assignment operator for many classes or many class hierarchies in your code.
You could delete the default copy constructor or default copy assignment operator for each base class, but that would be onerous and result in lots of duplicated code. Also, the deletion would get hidden among the base class methods.
A cleaner solution: create a class where the default copy constructor and/or default copy assignment operator are deleted. Derive all your classes or the base class of the class hierarchies from this special class. Copy construction and/or copy assignment will now be disabled for all these classes automatically.
Here is an example of such a special class:
class DelCopy
{public:
default;
DelCopy() = default;
~DelCopy() =
const DelCopy&) = delete;
DelCopy(operator=(DelCopy&) = delete;
DelCopy& };
Here is an example of deriving from the above class:
class A : DelCopy
{public:
int x) : x_(x)
A(
{}
int x_;
};
int main()
{10);
A a(// This copy construction will fail
A b(a); return 0;
}
Here is the gcc compiler error I got:
$ g++ tmp.cpp
tmp.cpp: In function βint main()β:
tmp.cpp:27:10: error: use of deleted function βA::A(const A&)β
A b(a);
^
tmp.cpp:13:7: note: βA::A(const A&)β is implicitly deleted because the default definition would be ill-formed:
class A : DelCopy
^
tmp.cpp:13:7: error: use of deleted function βDelCopy::DelCopy(const DelCopy&)β
tmp.cpp:9:5: note: declared here
DelCopy(const DelCopy&) = delete;
^~~~~~~
Note that this only disables the default copy constructor and/or copy assignment operator. You cannot stop a child class from defining a custom copy constructor and/or copy assignment.