Code Yarns β€πŸ‘¨β€πŸ’»
Tech Blog ❖ Personal Blog

How to disable default copy constructor or assignment in C++

πŸ“… 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:
    DelCopy() = default;
    ~DelCopy() = default;

    DelCopy(const DelCopy&) = delete;
    DelCopy& operator=(DelCopy&) = delete;
};

Here is an example of deriving from the above class:

class A : DelCopy
{
public:
    A(int x) : x_(x)
    {}

    int x_;
};

int main()
{
    A a(10);
    A b(a); // This copy construction will fail
    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.


Β© 2022 Ashwin Nanjappa β€’ All writing under CC BY-SA license β€’ 🐘 @codeyarns@hachyderm.io β€’ πŸ“§