c++ - 缺少删除默认构造函数(和复制控制成员)的规则?

标签 c++

我的 c++ 书(lippman,c++ primer,第五版,第 508 页)提供了这 4 条规则,用于确定编译器何时将复制控制和默认构造函数合成为已删除的成员:

  • The synthesized destructor is defined as deleted if the class has a member whose own destructor is deleted or inaccessible (e.g. private).

  • The synthesized copy constructor is defined as deleted if the class has a member whose own copy constructor is deleted or inaccessible. It is also deleted if the class has a member with a deleted or inaccessible destructor.

  • The synthesized copy-assignment operator is defined as deleted if a member has a deleted or inaccessible copy-assignment operator, or if the class has a const or reference member.

  • The synthesized default constructor is defined as deleted if the class has a member with a deleted or inaccessible destructor; or has a reference member that does not have an in-class initializer; or has a const member whose type does not explicitly define a default constructor and that member does not have an in-class initializer.

我没看到这些规则如何解释此处的第二个错误:

class Foo {
public:
  Foo(int i) { }
};

class Bar {
private:
  Foo foo;
};

int main() {
  Foo foo; //error: no matching constructor in Foo
  Bar bar; //error: implicitly deleted constructor in Bar
  return 0;
}

第一个错误可以理解,与本题没有直接关系。第二个错误令人惊讶,因为上述规则没有解释为什么 Bar 应该将其默认构造函数合成为删除。

我的书缺少什么规则,或者我没有掌握规则?

最佳答案

Foo 没有默认构造函数,因为您声明了一个构造函数;来自 C++11 12.1/5:

If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted

Bar 有一个删除的默认构造函数,因为 Foo 没有默认构造函数;来自 C++11 12.1/5(第 5 个要点):

A defaulted default constructor for class X is defined as deleted if [...] any [...] non-static data member [...] has no default constructor

您引用的“规则”似乎忽略了这一点,只在第三个要点中提到了 const 合格成员的情况。

关于c++ - 缺少删除默认构造函数(和复制控制成员)的规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14566341/

相关文章:

c++ - Windbg 条件断点未按预期工作,我的语法是否正确?

c++ - boost 单元测试模板会产生臃肿的代码。如何避免这种情况?

c++ - 将 std::ofstream 设置为 zip 存档文件

c++ - 对 std::set 的迭代不会结束

c++ - VS 2012 中有什么可以改变来破坏我的 C++ 应用程序?

c++ - "position"是 C++ 中的保留字吗?

c++ - 将 void* 转换为 const void**

c++ - 将 args 应用于函数的模板函数

c++ - 为什么这个简单的功能没有去虚拟化?

c++ - "extern __forceinline "是什么 C++ 习语?