2

Why would one prefer to use a private copy constructor over deleting the copy constructor in C++?

E.g.:

class Entity
{
private:
    Entity(const Entity &copy) // <== private copy constructor
    {
       /* do copy stuff */
    }
public:
    /* more code here... */
}

As opposed to:

class Entity
{
public:
    Entity(const Entity &copy) = delete; // <== copy constructor deleted

    /* more code here... */
}

Related questions that don't quite answer what I'm asking:

What's the use of the private copy constructor in c++

Deleted vs empty copy constructor

camercu
  • 147
  • 7
  • 3
    To be compatible with C++98. – melpomene Nov 03 '18 at 01:31
  • private copy ctor can be used in other member functions. if resource of the class is unique, the delete can ne used. for example, you can make copy ctor private, and provide a public clone function to outside – rsy56640 Nov 03 '18 at 01:32

1 Answers1

3

2 possible reasons:

  • you cannot use C++11 or later

  • you need objects of the class to be copyable by methods of the class or it's friends, but not by anything else

Slava
  • 43,454
  • 1
  • 47
  • 90
  • could you please provide an example construct of where you might want an instance to be able to copy, where you wouldn't want outsiders to do so? – camercu Nov 03 '18 at 02:01
  • 1
    @camercu A linked list `node`. The only classes who should be able to create a `node` are `node`s and the linked list, a `friend` of the `node`. – user4581301 Nov 03 '18 at 06:35