3

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

2
  • 3
    To be compatible with C++98. Commented Nov 3, 2018 at 1: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 Commented Nov 3, 2018 at 1:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 A linked list node. The only classes who should be able to create a node are nodes and the linked list, a friend of the node.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.