Private Copy Designer: Deny

I program in an open source library that has very few comments in the code, and absolutely no documentation related to the code, or comments that show absolutely nothing or are confusing. An example library class is sometimes defined as follows (this is an abstract short example):

class A { private: // Disallow default bitwise copy construct. A (const A& Acopy) { data = Acopy.data; }; int data; public: A() {}; A (int arg) : data(arg) {}; A(const A& Acopy) { data = Acopy.data; }; }; 

The "Deny default bitmap" comment before the private constructor will indicate that when I define the type, I need to define my own copy constructor to avoid the one generated "for me ambiguously by the compiler. This is what I have learned so far on this topic, but in this case the constructor is private , and compilation is interrupted in this form.

Q: Is there a reason for such a thing? A copy constructor that is private? And what does this comment mean?

Tomislav

+4
source share
5 answers

That means what you said. Typically, the compiler generates a copy constructor. To prevent this, you can define your own and make it private. Then any attempt to copy-build the class will not be performed at compile time, and not quietly do the wrong thing.

+9
source

Typically, the copy constructor closes to prevent objects from being passed by value.

+2
source

I think compilation breaks because the copy constructor is defined twice, once as closed and once as open.

The reason for the private copy constructor might be to prevent passing or returning instance A to a value. Why would this have to be done, this is another matter to which I cannot answer.

+2
source

The point is, as you said, to avoid generating copy constructors by default, but not only that - it's private to avoid using it. What makes it private is to not allow it to be used.

+2
source

Compilation is interrupted because you have two copy constructors, one open and one closed. Personal copy services are perfectly in order. They prohibit many dangerous things that the user can do.

0
source

All Articles