自动生成默认/复制/移动向量和复制/移动赋值运算符的条件?
我想刷新我对编译器通常自动生成默认构造函数、复制构造函数和赋值运算符的条件的记忆。
我记得有一些规则,但我不记得了,而且也无法在网上找到信誉良好的资源。有人可以帮忙吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在下文中,“自动生成”的意思是“隐式声明为默认,但未定义为删除”。在某些情况下,声明了特殊成员函数,但定义为已删除。
仅 C++11 及更高版本:
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.
C++11 and later only:
我发现下图非常有用。
来自粘性位 - 成为零英雄的规则
I've found the diagram below very useful.
from Sticky Bits - Becoming a Rule of Zero Hero
C++17 N4659 标准草案
如需快速交叉标准参考,请查看以下 cppreference 条目的“隐式声明”部分:
当然可以从标准中获得相同的信息。例如 C++17 N4659 标准草案:
15.8.1 “复制/移动构造函数”表示复制构造函数:
对于移动构造函数:
15.8.2“复制/移动赋值运算符”对于复制赋值表示:
对于移动分配:
15.4“析构函数”对于析构函数是这样说的:
C++17 N4659 standard draft
For a quick cross standard reference, have a look at the "Implicitly-declared" sections of the following cppreference entries:
The same information can of course be obtained from the standard. E.g. on C++17 N4659 standard draft:
15.8.1 "Copy/move constructors" says for for copy constructor:
and for move constructor:
15.8.2 "Copy/move assignment operator" says for copy assignment:
and for move assignment:
15.4 "Destructors" says it for destructors:
Howard Hinnant 的下图很好地总结了所有规则。
红细胞是已弃用的行为(请参阅 [depr.impldec]),并且可能会更改在某个时刻
删除
。来源:Howard Hinnant - 我如何声明我的
class
以及原因The following graphic by Howard Hinnant sums all the rules up nicely.
Red cells are deprecated behavior (see [depr.impldec]) and may be changed to
deleted
at some point.Source: Howard Hinnant - How I Declare My
class
And Why