在 C++11 中三分法变成五分法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4782757/
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:28:13  来源:igfitidea点击:

Rule-of-Three becomes Rule-of-Five with C++11?

c++constructorc++11rvalue-referencerule-of-three

提问by Xeo

So, after watching this wonderful lectureon rvalue references, I thought that every class would benefit of such a "move constructor", template<class T> MyClass(T&& other)editand of course a "move assignment operator", template<class T> MyClass& operator=(T&& other)as Philipp points out in his answer, if it has dynamically allocated members, or generally stores pointers. Just like you shouldhave a copy-ctor, assignment operator and destructor if the points mentioned before apply. Thoughts?

因此,在观看了关于右值引用的精彩讲座后,我认为每个类都会受益于这样的“移动构造函数”,template<class T> MyClass(T&& other)编辑,当然还有“移动赋值运算符”,template<class T> MyClass& operator=(T&& other)正如 Philipp 在他的回答中指出的那样,如果它已经动态分配了成员,或通常存储指针。就像你应该有一个复制构造函数、赋值运算符和析构函数一样,如果前面提到的点适用。想法?

采纳答案by Philipp

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, 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 a 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

请注意,不会为显式声明任何其他特殊成员函数的类生成移动构造函数和移动赋值运算符,不会为显式声明移动构造函数或移动的类生成复制构造函数和复制赋值运算符赋值运算符,并且具有显式声明的析构函数和隐式定义的复制构造函数或隐式定义的复制赋值运算符的类被视为已弃用。特别是,以下完全有效的 C++03 多态基类

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 (automatic generation of all special member functions).

有点烦人,但可能比替代方法更好(自动生成所有特殊成员函数)。

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.

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

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. If you have a move constructor and move assignment operator, specializing std::swapwill become unimportant because the generic std::swapuses the move constructor and move assignment operator if available, and that should be fast enough.

对于资源管理类,如果无法复制底层资源,您可以将复制构造函数和复制赋值运算符定义为已删除(这算作定义)。通常您仍然需要移动构造函数和移动赋值运算符。复制和移动赋值运算符通常使用 来实现swap,就像在 C++03 中一样。如果您有移动构造函数和移动赋值运算符,则专门化std::swap将变得不重要,因为泛型std::swap使用移动构造函数和移动赋值运算符(如果可用),并且应该足够快。

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.

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

回答by NoSenseEtAl

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_ptrand std::shared_ptr. Through the use of custom deleter objects, both have been made flexible enough to manage virtually any kind of resource.

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

回答by Motti

I don't think so, the rule of threeis 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
  1. 复制构造函数
  2. 赋值运算符
  3. 析构函数

However leaving out the move constructor or move assignment operator does not imply a bug. It maybe 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.

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

回答by peoro

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).

  • 这只是一个优化。

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

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

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

回答by Andrey Rekalo

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

以下是自 11 年 1 月 24 日以来当前状态和相关发展的简短更新。

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

根据 C++11 标准(参见附录 D 的 [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 proposedto 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.

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

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

最近,有人再次提议调整 C++11 的措辞,以实现非正式的五法则,即

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.

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

回答by sellibitze

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".

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

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 allrelated 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.

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

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.

由于关于编译器生成的特殊函数和 C++03 兼容性的限制性规则,三规则保持三规则。

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

以下是一些适用于最新 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&&);
};

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:

现在预计 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;
};

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

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

回答by CashCow

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.

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

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

3 法则意味着如果你实现了一个,你必须实现所有 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.

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

回答by Puppy

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 allclasses are copyable and movable, some are just movable, some are just copyable.

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