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

I think this is impossible, but I can ask. Can I declare a private Copy-Constructor and use the standard implementation?

Background: I have a class with very large vectors, and I do not want to call the copy constructor, except for one member function. Using the standard public copy-ctor can easily lead to errors, for example, for example. forgetting the link in iteration ( foreach(Type el,vectOfBigObjects) instead foreach(Type const& el,vectOfBigObjects)). So I want to keep the standard constructor, but just make it private.

Is this possible without rewriting the definition of copy-ctors?

+5
source share
1 answer

Is this possible without rewriting the definition of copy-ctors?

++ 11 . :

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

, , , private. :

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!
}

.

, ( ) , . , , X .

+11

All Articles