Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the difference between declaring a constructor private and =delete?

For example, I want to declare a class but I want the client to not be able to use the copy constructor (or copy assignment operator)

Both of the following two does not allow the use of the copy constructor:

1.

class Track
{
public:
  Track(){};
  ~Track(){};
private:
  Track(const Track&){};
};

2.

class Track
{
public:
  Track(){};
  ~Track(){};
  Track(const Track&)=delete;
};

Is one of these ways "more correct" than the other or are equal? Is there any side-effect?

//Does not compile with both the above ways
int main()
{
  Track l;
  Track p(l);
}
like image 828
Avraam Mavridis Avatar asked May 26 '13 10:05

Avraam Mavridis


People also ask

What is constructor delete in C++?

In another way, = delete means that the compiler will not generate those constructors when declared and this is only allowed on copy constructor and assignment operator. There is also = 0 usage; it means that a function is purely virtual and you cannot instantiate an object from this class.

What happens if we declare constructor as private in C++?

In your code, the program cannot run since you have defined a constructor and it is private. Therefore, in your current code, there is no way to create objects of the class, making the class useless in a sense.

What is private constructor in C++ with example?

A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class. For example: C# Copy.


2 Answers

Making it private is the "old" way of doing it. The constructor still exists, but it is private, and can only be invoked from within another class member function.

= delete deletes the constructor. It is not generated by the compiler, and it simply will not exist.

So most likely, = delete is what you want. (although with the caveat that not all compilers support this syntax yet, so if portability is a concern...)

like image 57
jalf Avatar answered Oct 18 '22 04:10

jalf


Declaring a copy constructor private still allows member functions of the Track class to copy-construct instances of that class, while making it deleted simply forbids copy-constructing that object.

In C++11, deleting a copy constructor is the right way to express the fact that a class is non-copyable (unless of course it makes sense for you to let member functions of Track, or friends of Track, to copy-construct Track objects).

like image 8
Andy Prowl Avatar answered Oct 18 '22 03:10

Andy Prowl