编译生成的构造函数

Hol*_*mar 11 c++ copy-constructor default-constructor assignment-operator

这只是一个快速的问题,可以正确理解当您使用如下构造函数创建类时会发生什么:

class A
{
  public:
    A() {}
};
Run Code Online (Sandbox Code Playgroud)

我知道没有生成默认构造函数,因为它已经定义,但是由编译器生成的复制和赋值构造函数,或者换句话说,我是否需要声明私有复制构造函数和私有赋值运算符以防止这种情况发生?

class A
{
  private:
    // needed to prevent automatic generation?
    A( const A& );
    A& operator=( const A& );
  public:
    A() {}
};
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 13

是的,即使您声明自己的默认构造函数,仍会创建复制构造函数和复制赋值运算符.

只有在类定义中分别声明自己的复制构造函数或复制赋值运算符时,才会禁止创建它们.

请注意,可以同时拥有自己的复制构造函数和编译器:

struct A {
  A() { }
  A(A const&, int foo); 
}; // compiler declares a copy constructor now

// make the second parameter have a default argument
// now this constructor is a copy constructor too. 
inline A::A(A const&, int foo = 0) {

}

int main() {
  A a;
  A b = a; // ambiguity between compiler's one and our custom one!
}
Run Code Online (Sandbox Code Playgroud)

但是,标准允许编译器接受此代码 - 但效果类似于具有未定义的行为:程序格式错误,但该程序不需要警告/错误.(早期GCC版本不拒绝此代码,最近的代码拒绝它).


GMa*_*ckG 12

是.无论其他构造函数和运算符如何,始终都会创建复制构造函数,赋值运算符和析构函数.

如果你想禁用它,那么你所拥有的就是完美的.这也很常见.