Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make the copy constructor private and still use the default implementation

I think this impossible but I might as well ask. Can I declare a private Copy-Constructor and still use the default implementation?

Background: I have a class with very big vectors and I do not want to call the copy constructor except for one member function. Using a standard public copy-ctor might easily lead to bugs like e.g. forgetting a reference in an iteration (foreach(Type el,vectOfBigObjects) instead of foreach(Type const& el,vectOfBigObjects)). Hence I want to keep the standard copy consructor but just make it private.

Is this possible without rewriting the copy-ctors definition ?

like image 403
Martin Avatar asked Apr 07 '13 14:04

Martin


1 Answers

Is this possible without rewriting the copy-ctors definition ?

In C++11, yes. You just have to declare the constructor and mark it as defaulted:

struct X
{
    // ...
private:
    X(X const&) = default;
};

This will define a copy constructor which would have the same definition as an implicitly generated one, but will be private. For instance:

struct X
{
    X() { } // Required because a user-declared constructor in
            // the definition of X inhibits the implicit generation
            // of a default constructor (even if the definition is
            // defaulted!)

    void foo()
    {
        // ...
        X tmp = *this; // OK!
        // ...
    }

private:

    X(X const&) = default; // Default definition, accessible to
                           // member functions of X only!
};

int main()
{
     X x;
     // X x2 = x; // ERROR if uncommented!
}

Here is a live example.

Notice, that a user-declared constructor (including copy constructor) in a class definition inhibits the implicit generation of a default constructor, even if its definition is defaulted. This is why, for instance, I had to explicitly declare X's default constructor in the example above.

like image 114
Andy Prowl Avatar answered Oct 13 '22 00:10

Andy Prowl