我可以将复制构造函数设为私有,并仍使用默认实现

时间:2013-04-07 14:54:36

标签: c++ copy-constructor

我认为这是不可能的,但我不妨问一下。 我可以声明一个私有的Copy-Constructor并仍然使用默认实现吗?

背景:我有一个非常大的向量类,我不想调用复制构造函数,除了一个成员函数。使用标准的公共副本可能 很容易导致像忘记迭代中的引用(foreach(Type el,vectOfBigObjects)而不是foreach(Type const& el,vectOfBigObjects))。因此,我想保留标准的复制品,但只是将其设为私有。

这是否可以在不重写copy-ctors定义的情况下实现?

1 个答案:

答案 0 :(得分:11)

  

这是否可以在不重写copy-ctors定义的情况下实现?

在C ++ 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!
}

这是live example

请注意,类定义中的用户声明的构造函数(包括复制构造函数)禁止隐式生成默认构造函数,即使其定义是默认的。这就是为什么,例如,我必须在上面的例子中明确声明X的默认构造函数。