C++11 的三规则变成五规则?

发布于 2024-10-14 03:38:51 字数 1699 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

烟织青萝梦 2024-10-21 03:38:51

我想说,三法则变成了三、四、五法则:

每个类都应该明确定义一个
以下一组特殊成员中的
功能:

  • 析构函数、复制构造函数、复制赋值运算符

此外,每个显式定义析构函数的类都可以显式定义移动构造函数和/或移动赋值运算符。

通常,以下一组特殊成员之一
函数是合理的:

  • 无(对于许多简单的类,其中隐式生成的特殊成员函数正确且快速)
  • 析构函数、复制构造函数、复制赋值运算符(在本例中为
    班级不可移动)
  • 析构函数、移动构造函数、移动赋值运算符(在这种情况下,类将不可复制,对于底层资源不可复制的资源管理类很有用)
  • 析构函数、复制构造函数、复制赋值运算符、移动构造函数(由于复制省略,如果复制赋值运算符按值获取其参数,则不会产生任何开销)
  • 析构函数、复制构造函数、复制赋值运算符、移动构造函数、
    移动赋值运算符

注意:

  • 对于显式声明任何其他特殊成员函数(例如析构函数、复制构造函数或移动赋值运算符)的类,不会生成移动构造函数和移动赋值运算符。 。
  • 对于显式声明移动构造函数或移动赋值运算符的类,不会生成该复制构造函数和复制赋值运算符。
  • 并且具有显式声明的析构函数和隐式定义的复制构造函数或隐式定义的复制赋值运算符的类被视为已弃用。

特别是,以下完全有效的 C++03 多态基类:

class C {
  virtual ~C() { }   // allow subtype polymorphism
};

应该重写如下:

class C {
  C(const C&) = default;               // Copy constructor
  C(C&&) = default;                    // Move constructor
  C& operator=(const C&) = default;  // Copy assignment operator
  C& operator=(C&&) = default;       // Move assignment operator
  virtual ~C() { }                     // Destructor
};

有点烦人,但可能比替代方案更好(在这种情况下,自动生成仅用于复制的特殊成员函数强>,没有移动的可能性)。

与三巨头规则相反,不遵守该规则可能会导致严重损害,不明确声明移动构造函数和移动赋值运算符通常很好,但在效率方面通常不是最佳的。如上所述,仅当没有显式声明的复制构造函数、复制赋值运算符或析构函数时,才会生成移动构造函数和移动赋值运算符。这与自动生成复制构造函数和复制赋值运算符的传统 C++03 行为不对称,但更安全。因此,定义移动构造函数和移动赋值运算符的可能性非常有用,并且创造了新的可能性(纯粹的可移动类),但是遵守 C++03 三巨头规则的类仍然没问题。

对于资源管理类,如果无法复制基础资源,您可以将复制构造函数和复制赋值运算符定义为已删除(算作定义)。通常您仍然需要移动构造函数和移动赋值运算符。复制和移动赋值运算符通常使用 swap 来实现,如 C++03 中那样。谈论交换;如果我们已经有一个移动构造函数和移动赋值运算符,专门化std::swap将变得不重要,因为通用的std::swap使用移动构造函数和移动赋值运算符(如果可用)(并且应该足够快)。

不用于资源管理(即没有非空析构函数)或子类型多态性(即没有虚拟析构函数)的类不应声明这五个特殊成员函数中的任何一个;它们都是自动生成的,并且行为正确且快速。

I'd say the Rule of Three becomes the Rule of Three, Four and Five:

Each class should explicitly define exactly one
of the following set of special member
functions:

  • None
  • Destructor, copy constructor, copy assignment operator

In addition, each class that explicitly defines a destructor may explicitly define a move constructor and/or a move assignment operator.

Usually, one of the following sets of special member
functions is sensible:

  • None (for many simple classes where the implicitly generated special member functions are correct and fast)
  • Destructor, copy constructor, copy assignment operator (in this case the
    class will not be movable)
  • Destructor, move constructor, move assignment operator (in this case the class will not be copyable, useful for resource-managing classes where the underlying resource is not copyable)
  • Destructor, copy constructor, copy assignment operator, move constructor (because of copy elision, there is no overhead if the copy assignment operator takes its argument by value)
  • Destructor, copy constructor, copy assignment operator, move constructor,
    move assignment operator

Note:

  • That move constructor and move assignment operator won't be generated for a class that explicitly declares any of the other special member functions (like destructor or copy-constructor or move-assignment operator).
  • That copy constructor and copy assignment operator won't be generated for a class that explicitly declares a move constructor or move assignment operator.
  • And that a class with an explicitly declared destructor and implicitly defined copy constructor or implicitly defined copy assignment operator is considered deprecated.

In particular, the following perfectly valid C++03 polymorphic base class:

class C {
  virtual ~C() { }   // allow subtype polymorphism
};

Should be rewritten as follows:

class C {
  C(const C&) = default;               // Copy constructor
  C(C&&) = default;                    // Move constructor
  C& operator=(const C&) = default;  // Copy assignment operator
  C& operator=(C&&) = default;       // Move assignment operator
  virtual ~C() { }                     // Destructor
};

A bit annoying, but probably better than the alternative (in this case, automatic generation of special member functions for copying only, without move possibility).

In contrast to the Rule of the Big Three, where failing to adhere to the rule can cause serious damage, not explicitly declaring the move constructor and move assignment operator is generally fine but often suboptimal with respect to efficiency. As mentioned above, move constructor and move assignment operators are only generated if there is no explicitly declared copy constructor, copy assignment operator or destructor. This is not symmetric to the traditional C++03 behavior with respect to auto-generation of copy constructor and copy assignment operator, but is much safer. So the possibility to define move constructors and move assignment operators is very useful and creates new possibilities (purely movable classes), but classes that adhere to the C++03 Rule of the Big Three will still be fine.

For resource-managing classes you can define the copy constructor and copy assignment operator as deleted (which counts as definition) if the underlying resource cannot be copied. Often you still want move constructor and move assignment operator. Copy and move assignment operators will often be implemented using swap, as in C++03. Talking about swap; if we already have a move-constructor and move-assignment operator, specializing std::swap will become unimportant, because the generic std::swap uses the move-constructor and move-assignment operator if available (and that should be fast enough).

Classes that are not meant for resource management (i.e., no non-empty destructor) or subtype polymorphism (i.e., no virtual destructor) should declare none of the five special member functions; they will all be auto-generated and behave correct and fast.

薄荷梦 2024-10-21 03:38:51

我不敢相信没有人链接到 这个

基本上文章主张“零规则”。
我不适合引用整篇文章,但我相信这是要点:

具有自定义析构函数、复制/移动构造函数或复制/移动赋值运算符的类应专门处理所有权。
其他类不应该有自定义析构函数、复制/移动
构造函数或复制/移动赋值运算符。

恕我直言,这一点也很重要:

常见的“包中所有权”类包含在标准中
库:std::unique_ptr 和 std::shared_ptr。通过使用
自定义删除器对象,两者都足够灵活以管理
几乎任何类型的资源。

I can't believe that nobody linked to this.

Basically article argues for "Rule of Zero".
It is not appropriate for me to quote entire article but I believe this is the main point:

Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership.
Other classes should not have custom destructors, copy/move
constructors or copy/move assignment operators.

Also this bit is IMHO important:

Common "ownership-in-a-package" classes are included in the standard
library: std::unique_ptr and std::shared_ptr. Through the use of
custom deleter objects, both have been made flexible enough to manage
virtually any kind of resource.

秋风の叶未落 2024-10-21 03:38:51

我不这么认为,三法则是根据经验,实现以下其中一项但不是全部的类可能存在错误。

  1. 复制构造函数
  2. 赋值运算
  3. 符 析构函数

但是,省略移动构造函数或移动赋值运算符并不意味着存在错误。 可能是错过了优化机会(在大多数情况下),或者移动语义与此类不相关,但这不是错误。

虽然在相关时定义移动构造函数可能是最佳实践,但这不是强制性的。在许多情况下,移动构造函数与类无关(例如 std::complex),并且在 C++03 中行为正确的所有类将继续在 C++ 中行为正确0x,即使他们没有定义移动构造函数。

I don't think so, the rule of three is a rule of thumb that states that a class that implements one of the following but not them all is probably buggy.

  1. Copy constructor
  2. Assignment operator
  3. Destructor

However leaving out the move constructor or move assignment operator does not imply a bug. It may be a missed opportunity at optimization (in most cases) or that move semantics aren't relevant for this class but this isn't a bug.

While it may be best practice to define a move constructor when relevant, it isn't mandatory. There are many cases in which a move constructor isn't relevant for a class (e.g. std::complex) and all classes that behave correctly in C++03 will continue to behave correctly in C++0x even if they don't define a move constructor.

剧终人散尽 2024-10-21 03:38:51

是的,我认为为此类类提供一个移动构造函数会很好,但请记住:

  • 这只是一种优化。

    仅实现复制构造函数、赋值运算符或析构函数中的一两个可能会导致错误,而没有移动构造函数则可能会降低性能。

  • 移动构造函数不能总是在不进行修改的情况下应用。

    某些类总是分配其指针,因此此类类总是在析构函数中删除其指针。在这些情况下,您需要添加额外的检查来说明它们的指针是否已分配或已移走(现在为空)。

Yes, I think it would be nice to provide a move constructor for such classes, but remember that:

  • It's only an optimization.

    Implementing only one or two of the copy constructor, assignment operator or destructor will probably lead to bugs, while not having a move constructor will just potentially reduce performance.

  • Move constructor cannot always be applied without modifications.

    Some classes always have their pointers allocated, and thus such classes always delete their pointers in the destructor. In these cases you'll need to add extra checks to say whether their pointers are allocated or have been moved away (are now null).

吝吻 2024-10-21 03:38:51

以下是自 2011 年 1 月 24 日以来的现状和相关进展的简短更新。

根据 C++11 标准(参见附录 D 的 [depr.impldec]):

如果类具有用户声明的复制赋值运算符或用户声明的析构函数,则不推荐使用复制构造函数的隐式声明。如果类具有用户声明的复制构造函数或用户声明的析构函数,则不推荐使用复制赋值运算符的隐式声明。

实际上提议废弃已弃用的行为为 C++14 提供真正的“五规则”,而不是传统的“三规则”。2013 年,EWG 投票反对在 C++2014 中实施这一提案。做出该提案决定的主要理由与对破坏现有代码的普遍担忧有关。

最近再次提议适配C+ +11 措辞以实现非正式的五规则,即

如果任何这些函数是用户提供的,则编译器不会生成任何复制函数、移动函数或析构函数。

如果得到 EWG 批准,该“规则”很可能会被 C++17 采用。

Here's a short update on the current status and related developments since Jan 24 '11.

According to the C++11 Standard (see Annex D's [depr.impldec]):

The implicit declaration of a copy constructor is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor. The implicit declaration of a copy assignment operator is deprecated if the class has a user-declared copy constructor or a user-declared destructor.

It was actually proposed to obsolete the deprecated behavior giving C++14 a true “rule of five” instead of the traditional “rule of three”. In 2013 the EWG voted against this proposal to be implemented in C++2014. The major rationale for the decision on the proposal had to do with general concerns about breaking existing code.

Recently, it has been proposed again to adapt the C++11 wording so as to achieve the informal Rule of Five, namely that

no copy function, move function, or destructor be compiler-generated if any of these functions is user-provided.

If approved by the EWG, the "rule" is likely to be adopted for C++17.

涙—继续流 2024-10-21 03:38:51

基本上是这样的:如果你不声明任何移动操作,你应该遵守三规则。如果声明移动操作,“违反”三规则并没有什么坏处,因为编译器生成的操作的生成已经变得非常严格。即使您没有声明移动操作并违反了“三”规则,如果用户声明了一个特殊函数并且由于以下原因自动生成了其他特殊函数,C++0x 编译器也应该向您发出警告:现在已弃用“C++03 兼容性规则”。

我认为可以肯定地说,这条规则变得不那么重要了。 C++03 中的真正问题是,实现不同的复制语义需要用户声明所有 相关的特殊函数,以便它们都不是编译器生成的(否则会做错误的事情)。但C++0x改变了特殊成员函数生成的规则。如果用户仅声明这些函数之一来更改复制语义,它将阻止编译器自动生成其余的特殊函数。这很好,因为缺少声明现在会将运行时错误转变为编译错误(或至少是警告)。作为 C++03 兼容性措施,某些操作仍然会生成,但这一代被视为已弃用,并且至少应该在 C++0x 模式下产生警告。

由于有关编译器生成的特殊函数和 C++03 兼容性的相当严格的规则,三规则仍然是三规则。

以下是一些适合最新 C++0x 规则的示例:

template<class T>
class unique_ptr
{
   T* ptr;
public:
   explicit unique_ptr(T* p=0) : ptr(p) {}
   ~unique_ptr();
   unique_ptr(unique_ptr&&);
   unique_ptr& operator=(unique_ptr&&);
};

在上面的示例中,无需将任何其他特殊函数声明为已删除。由于限制性规则,它们根本不会生成。用户声明的移动操作的存在会禁用编译器生成的复制操作。但在这样的情况下:

template<class T>
class scoped_ptr
{
   T* ptr;
public:
   explicit scoped_ptr(T* p=0) : ptr(p) {}
   ~scoped_ptr();
};

C++0x 编译器现在预计会生成有关编译器生成的可能会执行错误操作的复制操作的警告。在这里,三件事的规则应该得到尊重。在这种情况下,警告是完全适当的,并且使用户有机会处理错误。我们可以通过删除函数来解决这个问题:

template<class T>
class scoped_ptr
{
   T* ptr;
public:
   explicit scoped_ptr(T* p=0) : ptr(p) {}
   ~scoped_ptr();
   scoped_ptr(scoped_ptr const&) = delete;
   scoped_ptr& operator=(scoped_ptr const&) = delete;
};

因此,三规则在这里仍然适用,仅仅是因为 C++03 兼容性。

Basically, it's like this: If you don't declare any move operations, you should respect the rule of three. If you declare a move operation, there is no harm in "violating" the rule of three as the generation of compiler-generated operations has gotten very restrictive. Even if you don't declare move operations and violate the rule of three, a C++0x compiler is expected to give you a warning in case one special function was user-declared and other special functions have been auto-generated due to a now deprecated "C++03 compatibility rule".

I think it's safe to say that this rule becomes a little less significant. The real problem in C++03 is that implementing different copy semantics required you to user-declare all related special functions so that none of them is compiler-generated (which would otherwise do the wrong thing). But C++0x changes the rules about special member function generation. If the user declares just one of these functions to change the copy semantics it'll prevent the compiler from auto-generating the remaining special functions. This is good because a missing declaration turns a runtime error into a compilation error now (or at least a warning). As a C++03 compatibility measure some operations are still generated but this generation is deemed deprecated and should at least produce a warning in C++0x mode.

Due to the rather restrictive rules about compiler-generated special functions and the C++03 compatibility, the rule of three stays the rule of three.

Here are some exaples that should be fine with newest C++0x rules:

template<class T>
class unique_ptr
{
   T* ptr;
public:
   explicit unique_ptr(T* p=0) : ptr(p) {}
   ~unique_ptr();
   unique_ptr(unique_ptr&&);
   unique_ptr& operator=(unique_ptr&&);
};

In the above example, there is no need to declare any of the other special functions as deleted. They simply won't be generated due to the restrictive rules. The presence of a user-declared move operations disables compiler-generated copy operations. But in a case like this:

template<class T>
class scoped_ptr
{
   T* ptr;
public:
   explicit scoped_ptr(T* p=0) : ptr(p) {}
   ~scoped_ptr();
};

a C++0x compiler is now expected to produce a warning about possibly compiler-generated copy operations that might do the wrong thing. Here, the rule of three matters and should be respected. A warning in this case is totally appropriate and gives the user the chance to handle the bug. We can get rid of the issue via deleted functions:

template<class T>
class scoped_ptr
{
   T* ptr;
public:
   explicit scoped_ptr(T* p=0) : ptr(p) {}
   ~scoped_ptr();
   scoped_ptr(scoped_ptr const&) = delete;
   scoped_ptr& operator=(scoped_ptr const&) = delete;
};

So, the rule of three still applies here simply because of the C++03 compatibility.

美胚控场 2024-10-21 03:38:51

我们不能说规则 3 现在变成规则 4(或 5)而不破坏所有执行规则 3 且不实现任何形式的移动语义的现有代码。

3 规则意味着如果您实施其中一项,则必须实施所有 3 条规则。

也不知道会有任何自动生成的移动。 “3 规则”的目的是因为它们自动存在,如果您实现其中一个,那么其他两个的默认实现很可能是错误的。

We cannot say that rule of 3 becomes rule of 4 (or 5) now without breaking all existing code that does enforce rule of 3 and does not implement any form of move semantics.

Rule of 3 means if you implement one you must implement all 3.

Also not aware there will be any auto-generated move. The purpose of "rule of 3" is because they automatically exist and if you implement one, it is most likely the default implementation of the other two is wrong.

溺孤伤于心 2024-10-21 03:38:51

在一般情况下,那么是的,三规则变成了五规则,添加了移动赋值运算符和移动构造函数。但是,并非所有类都是可复制和可移动的,有些类只是可移动的,有些只是可复制的。

In the general case, then yes, the rule of three just became the of five, with the move assignment operator and move constructor added in. However, not all classes are copyable and movable, some are just movable, some are just copyable.

爱情眠于流年 2024-10-21 03:38:51

简单来说,只要记住这一点即可。

0 规则

类既没有自定义析构函数、复制/移动构造函数,也没有复制/移动赋值运算符。

3 规则
如果您实现其中任何一个的自定义版本,您就实现了所有这些。

析构函数、复制构造函数、复制赋值

5 规则
如果您实现自定义移动构造函数或移动赋值运算符,则需要定义所有 5 个。移动语义所需。

析构函数、复制构造函数、复制赋值、移动构造函数、移动赋值

四个半规则
与 5 规则相同,但具有复制和交换习惯用法。通过包含交换方法,复制赋值和移动赋值合并为一个赋值运算符。

析构函数、复制构造函数、移动构造函数、赋值、交换(一半部分)

引用

https://www.linkedin.com/learning/c-plus-plus -高级主题/五规则?u=67551194
https://en.cppreference.com/w/cpp/language/rule_of_third

In simple terms, just remember this.

Rule of 0:

Classes have neither custom destructors, copy/move constructors or copy/move assignment operators.

Rule of 3:
If you implement a custom version of any of these, you implement all of them.

Destructor, Copy constructor, copy assignment

Rule of 5:
If you implement a custom move constructor or the move assignment operator, you need to define all 5 of them. Needed for move semantics.

Destructor, Copy constructor, copy assignment, move constructor, move assignment

Rule of four and a half:
Same as Rule of 5 but with copy and swap idiom. With the inclusion of the swap method, the copy assignment and move assignment merge into one assignment operator.

Destructor, Copy constructor, move constructor, assignment, swap (the half part)

References:

https://www.linkedin.com/learning/c-plus-plus-advanced-topics/rule-of-five?u=67551194
https://en.cppreference.com/w/cpp/language/rule_of_three

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文