Why should I make the constructor instance and assignment operator private and implemented in C ++?

Inspired by this question .

Usually, the reason for creating the copy and assignment operator private is to make the class not copied so that objects can be created and destroyed, but not copied - in most cases this happens because copying them does not make sense. In such cases, the copy constructor and assignment operator are private and not implemented - if the class is not copied, then no one should copy.

Is there a case where the copy constructor and assignment operator must be private and have a meaningful implementation at the same time?

+7
source share
3 answers

There are two cases at once:

  • friend s:

    Say that as part of your design, you have two highly connected classes where you need to copy another (say, like in the factory model or some of them), but you don’t want the whole world to be able to copy it.

  • packers:

    Suppose that you want to conditionally clone some element, depending on some internal behavior (for example, depending on some state with the class state) - the cleanest way, from the language point of view, is to separate the copy into your own functions anyway. This will ensure a good separation of problems.

+7
source

My guess is that this might be useful for a class containing a list of itself - then it can copy instances inside. This is really only useful for a class that is both an element and a container:

 class MyItems { private: /* Copy ctor and =operator */ List list; public: void AddItems(MyItems* items) { MyItems* added = new MyItems(items); list.Add(added); } }; 

Another thought is to allow cloning in circumstances controlled by the class. This can be useful when copying may make sense, but only under certain conditions or permissions:

 class MyClass { private: /* Copy ctor and =operator */ public: MyClass* clone() { if (canClone) { MyClass* cloned = new MyClass(this); return cloned; } else { return NULL; } } }; 
+7
source
  • We create a copy constructor and operator = does not implement so that even a friend cannot have any access to it. If you implement, it means you want friend have access. This is a constructive solution.
  • You want to do explicit cloning; that is, allow copying, but also make its code look dirty (something like casting in C ++ style operations in which there is dirt in your code )

eg.

 class A { A(const A& obj) { ... } A& operator = (const A& obj) { ... } public: A& clone(const A& obj) { *this = obj; return *this; } }; 

We put this clone() shell to allow the user to clone, however it also clearly shows what exactly he / she is doing.

+5
source

All Articles