为什么 C++11 隐式删除了我的默认构造函数?

Why C++11 implicitly deletes my default constructor?

在我从 boost::noncopyable 私下继承我的 class 之前,我想使用 C++11 使我的 class 不可复制。在 C++11 中,我实现了以下内容:

class Foo
{
public:
    Foo(const Foo&) = delete;
    Foo& operator=(const Foo&) = delete;
};

通过此更改编译客户端代码(使用 VS 2013)出现以下错误:

..\main.cpp(9): error C2512: 'Foo' : no appropriate default constructor available

我的客户端代码很简单:

int main()
{
    Foo foo;
}

是否有任何 C++11 规则隐式地删除默认构造函数

隐式默认构造函数没有被删除,如果你有其他构造函数,它只是不会生成。从很久以前就这样了。

C++03 [class.ctor]/5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a default constructor is implicitly declared.

C++11 [class.ctor]/5(与 C++14 相同):

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted

Foo 的默认构造函数没有删除,只是没有定义。显式 defaulted/deleted 构造函数是 用户声明的 构造函数,这会导致默认构造函数的隐式声明被禁止。 Foo 有一个 用户声明的 构造函数,显式删除的复制构造函数。

来自 N3337,§12.1/5 [class.ctor]

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). ...


请注意,如果确实删除了默认构造函数,则错误消息可能会说这么多。例如,如果我将 Foo 的定义更改为

class Foo
{
public:
    int &i;
};

引用类型的数据成员的存在隐式删除了默认构造函数。现在,clang and gcc produce the error messages

error: call to implicitly-deleted default constructor of 'Foo'

error: use of deleted function 'Foo::Foo()'

将这些与您的 original example

生成的错误消息进行比较

error: no matching constructor for initialization of 'Foo'
error: no matching function for call to 'Foo::Foo()'


要修复您的示例,您需要明确默认默认构造函数

Foo() = default;