Search code examples
c++privatecopy-constructorassignment-operator

in which case we need to disable default copy constructor and assign operator?


If we put copy constructor and assign operator as private and provide no implementation, they will be disabled, like this:

class Test
{
   private:
       Test(const Test&);
       Test& operator=(const Test&);
};

but in which case we need to do this? I mean when should we do it like this?


Solution

  • When you want the objects of this class to be non-copyable.

    There may be many reasons when objects can't be or shouldn't be copied to other objects. A few examples are:

    1. Log files
    2. Some mutices
    3. In Singleton pattern
    4. Object Factory
    5. Some versions of smart pointers

    For above examples, compiler provided version of default copy constructor and default assignment operators may lead to unexpected results.

    onwarnds, you can use =delete syntax to delete the compiler provided default versions.

    Another use is to force (restrict) copying of objects only via class utilities virtual Base* clone() for example.

    Related: Rule of three or rule of five