C++ 自动生成默认/复制/移动构造函数和复制/移动赋值运算符的条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4943958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:58:23  来源:igfitidea点击:

Conditions for automatic generation of default/copy/move ctor and copy/move assignment operator?

c++copy-constructordefault-constructormove-constructormove-assignment-operator

提问by oompahloompah

I want to refresh my memory on the conditions under which a compiler typically auto generates a default constructor, copy constructor and assignment operator.

我想刷新我对编译器通常自动生成默认构造函数、复制构造函数和赋值运算符的条件的记忆。

I recollect there were some rules, but I don't remember, and also can't find a reputable resource online. Can anyone help?

我记得有一些规则,但我不记得了,而且在网上也找不到信誉良好的资源。任何人都可以帮忙吗?

回答by Philipp

In the following, "auto-generated" means "implicitly declared as defaulted, but not defined as deleted". There are situations where the special member functions are declared, but defined as deleted.

在下文中,“自动生成”表示“隐式声明为默认值,但未定义为已删除”。在某些情况下,特殊成员函数已声明,但定义为已删除。

  • The default constructor is auto-generated if there is no user-declared constructor (§12.1/5).
  • The copy constructor is auto-generated if there is no user-declared move constructor or move assignment operator (because there are no move constructors or move assignment operators in C++03, this simplifies to "always" in C++03) (§12.8/8).
  • The copy assignment operator is auto-generated if there is no user-declared move constructor or move assignment operator (§12.8/19).
  • The destructor is auto-generated if there is no user-declared destructor (§12.4/4).
  • 如果没有用户声明的构造函数(第 12.1/5 节),则默认构造函数是自动生成的。
  • 如果没有用户声明的移动构造函数或移动赋值运算符,复制构造函数将自动生成(因为在 C++03 中没有移动构造函数或移动赋值运算符,这在 C++03 中简化为“始终”)(第 12.8/8 节)。
  • 如果没有用户声明的移动构造函数或移动赋值运算符(第 12.8/19 节),则会自动生成复制赋值运算符。
  • 如果没有用户声明的析构函数(第 12.4/4 节),析构函数将自动生成。

C++11 and later only:

仅限 C++11 及更高版本:

  • The move constructor is auto-generated if there is no user-declared copy constructor, copy assignment operator or destructor, and if the generated move constructor is valid (§12.8/10).
  • The move assignment operator is auto-generated if there is no user-declared copy constructor, copy assignment operator or destructor, and if the generated move assignment operator is valid (e.g. if it wouldn't need to assign constant members) (§12.8/21).
  • 如果没有用户声明的复制构造函数、复制赋值运算符或析构函数,并且生成的移动构造函数有效(第 12.8/10 节),则移动构造函数是自动生成的。
  • 如果没有用户声明的复制构造函数、复制赋值运算符或析构函数,并且生成的移动赋值运算符有效(例如,如果它不需要分配常量成员)(第 12.8 节/ 21)。

回答by Marco M.

I've found the diagram below very useful.

我发现下面的图表非常有用。

C++ rules for automatic constructors and assignment operatorsfrom Sticky Bits - Becoming a Rule of Zero Hero

自动构造函数和赋值运算符的 C++ 规则来自Sticky Bits - 成为零英雄规则