Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a private copy constructor: disallow

I'm programming in an open source library which has very little comments in the code, and absolutely no code related documentation, or such comments which show absolutely nothing or are completely confusing. An example class of the library is sometimes defined as follows (this is an abstracted 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 comment "Dissalow default bitwise copy construct" in front of a private copy constructor would point to the fact that when I define a type I need to define my own copy constructor to avoid one being "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 the compilation breaks in this form.

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

Tomislav

like image 458
tmaric Avatar asked Jun 10 '11 07:06

tmaric


3 Answers

It means pretty much what you said. Normally, the compiler would generate a copy constructor. To prevent this, you can define your own, and make it private. Then any attempt at copy-constructing the class will fail at compile-time, rather than silently doing the wrong thing.

like image 62
jalf Avatar answered Sep 30 '22 01:09

jalf


Usually, A copy constructor is made private to disallow Passing of objects by value.

like image 38
Alok Save Avatar answered Sep 30 '22 01:09

Alok Save


The compilation breaks, I think, because the copy constructor is defined twice, once as private and once as public.

A reason for a private copy constructor might be to prevent an instance of A being passed or returned by value. Why one would want to do this is another matter, which I can't answer.

like image 24
Ted Hopp Avatar answered Sep 30 '22 01:09

Ted Hopp