336

So, after watching this wonderful lecture on rvalue references, I thought that every class would benefit of such a "move constructor", template<class T> MyClass(T&& other) edit and 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 should have a copy-ctor, assignment operator and destructor if the points mentioned before apply. Thoughts?

Flexo
  • 82,006
  • 22
  • 174
  • 256
Xeo
  • 123,374
  • 44
  • 277
  • 381
  • Some additional information can be found here http://brookspatola.com/the-rule-of-five-c11/ (just copying from deleted answer) – Aleks Jul 13 '16 at 13:55
  • Cripey. Your link to the "wonderful" lecture.... epic. I never saw this series before. – kevinarpe Aug 23 '16 at 14:56

8 Answers8

322

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

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.

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

Sebastian Mach
  • 36,158
  • 4
  • 87
  • 126
Philipp
  • 43,805
  • 12
  • 78
  • 104
  • @Xeo: In fact, if you pass by value, you can avoid having distinct copy and move assignment operators thanks to copy elision. – Philipp Jan 24 '11 at 14:19
  • 1
    @Philipp: Hm, right... a pass-by-value assignment operators 'other' would be move-constructed if you just implement the move-ctor if I got that right? And the remaining pointer copies and assignments would just be optimized by the compiler I think... – Xeo Jan 24 '11 at 14:33
  • 2
    @Xeo: I believe that if the class is not copyable, then you cannot pass instances of it by value even if the copy can be elided. In that case you should declare a true move assignment operator using a rvalue reference (an assignment operator that takes its argument by value is a copy assignment operator by §12.8/19, which you wouldn't want if the class is not copyable). For copyable and movable classes, the compiler should use copy elision or call the move constructor. – Philipp Jan 24 '11 at 14:42
  • Your list is imcomplete. For example, move ctor + dtor is also just fine. Also, the wording is imprecise. It's not about "having" a special function (w.r.t. preventing other compiler-generated ones). It's about the presence of *user-declared* special functions. – sellibitze Jan 24 '11 at 20:00
  • @sel: You're right, but I think there are few use cases where an explicitly defined move constructor without an explicitly defined move assignment operator makes sense. (Or can you think of one?) – Philipp Jan 24 '11 at 20:32
  • @Philipp - Why shouldn't the `C` destructor also be defaulted? – Omnifarious Feb 08 '11 at 19:01
  • 1
    @Omni: A virtual function cannot be explicitly defaulted on declaration (§8.4.2/2 and the last example in §8.4.2/5). – Philipp Feb 08 '11 at 19:50
  • @Philipp - Oh, that's interesting and odd. I wonder if there's a good reason for that rule. I mean, if you declare a destructor as pure virtual and don't provide an implementation, the compiler provides a default, so the rule seems odd to me. – Omnifarious Feb 08 '11 at 20:43
  • 10
    Have the rules changed ever since C++11 was passed? I believe `struct C { virtual ~C() = default; };` is now allowed and the most concise option. The prohibition ("- it shall not be virtual") from n3242 is not present anymore in n3290 and GCC allows it while previously it didn't. – Luc Danton Sep 21 '11 at 18:18
  • I think there is a typo in your code sample (can you check it?). `C& operator=(const C&) & = default;` should be `C& operator=(const C&) = default;` and `C& operator=(C&&) & = default;` should be `C& operator=(C&&) = default;` (mind the `&` sign before `default`) – BЈовић Feb 29 '12 at 09:26
  • 3
    @BЈовић No, it's not a typo. Here is a good explanation for it: http://stackoverflow.com/a/12306344/1174378 – Mihai Todor Sep 06 '12 at 19:00
  • 1
    What if you are adding a `std::unique_ptr<>` member in an other-wise POD struct and you wanted to make it *moveable* but *not copyable*. Could you end up with just 2 members (move assignment, move constructor)? (sry, I don't intend to be facetious - this is an actual situation that just came up for me!) Great answer, btw, I have +1 and starred this one. – kfmfe04 Mar 04 '13 at 08:21
  • @LucDanton I was wondering the same thing, but then I decided it might not matter. Wanting the default destructor is normally to keep your class POD. A virtual destructor destroys the POD-ness anyway, so I don't really see the benefit of "=default" in that case except "say what you mean" – Tim Seguine Oct 29 '13 at 20:21
  • @kfmfe04 If any of the members of your class are movable but not copyable (e.g. a unique_ptr), the compiler will implicitly define the move constructor and move assignment operator (but not the copy constructor or copy assignment operator). So `struct Foo { std::unique_ptr bar; }` is already movable! – ruds Apr 18 '14 at 19:50
  • 1
    Fine answer, only that polymorphic base class part looks wrong to me. Why the members are `private`? If `protected` was meant ... then destructor should not be `virtual`. If `public` was meant then do not you fear accidental object slicing with those public operators of base class? Especially copy assignment and move assignment should be `= delete` not `= default`. Typically polymorphic objects are not copyable or movable publicly. When copies are needed there is `virtual clone()`. Smart pointers pointing at objects are typically copied or moved instead. – Öö Tiib Sep 21 '14 at 15:34
69

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.

MultiplyByZer0
  • 4,341
  • 3
  • 27
  • 46
NoSenseEtAl
  • 23,776
  • 22
  • 102
  • 222
  • 4
    See [here](http://chat.stackoverflow.com/transcript/10?m=5255227#5255227) and [here](http://chat.stackoverflow.com/transcript/10?m=5255286#5255286) for my thoughts on this whole matter. :) – Xeo Dec 19 '12 at 12:33
19

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.

Motti
  • 99,411
  • 44
  • 178
  • 249
14

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

Community
  • 1
  • 1
peoro
  • 24,051
  • 18
  • 90
  • 141
  • 21
    It's not just an optimization, move semantics are important in perfect forwarding and some classes (`unique_ptr`) cannot be implemented without move semantics. – Puppy Jan 24 '11 at 14:17
  • @DeadMG: in general you're right, but in this context move semantics is just an optimization. Here I'm talking about already existing classes which respect the rule of three; `unique_ptr` and perfect forwarding are some special cases... – peoro Jan 24 '11 at 14:21
  • @peoro: That's like suggesting that C++ only adds classes to C. `auto_ptr` respected the rule of three, and `unique_ptr` most certainly does not respect a rule of five. – Puppy Jan 24 '11 at 14:26
  • 1
    @peoro: I think that a C++03 class that declares private copy constructor and copy assignment operators (or inherits from `boost::noncopyable`) can be called to obey the Rule of Three. (Otherwise we have to introduce different terminology, e.g. "Rule of the Big One and the Small Two"). – Philipp Jan 24 '11 at 14:26
  • I totally agree with you, but still I think these are special cases. I don't think the OP was thinking about `auto_ptr` or non copyable classes. This said, Philipp's answer is way better (more complete and stuff) than this one. – peoro Jan 24 '11 at 14:30
  • 4
    `some classes have always their pointers allocated...` in this case a move is usually implemented as a swap. Just as simple and fast. (Actually faster since it moves deallocation to the destructor of the rvalue) – Mooing Duck Aug 26 '11 at 19:11
8

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.

Andrey Rekalo
  • 191
  • 4
  • 9
  • 1
    Thanks for the update. As some of these C++ questions get old, it's helpful to see how question and/or answers are affected by newer language versions. – cb4 Apr 02 '16 at 15:26
4

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.

sellibitze
  • 25,788
  • 3
  • 69
  • 91
  • In fact, N3126 does define the copy constructor and copy assignment operator of `unique_ptr` as deleted—anybody knows why? – Philipp Jan 24 '11 at 20:49
  • @Philipp: The restrictive rules are newer than N3126. However, N3225 still declares the copy operations of unique_ptr as deleted. This is not necessary anymore, but it's also not wrong. So, there is no real need to change the spec of unique_ptr. – sellibitze Jan 24 '11 at 21:58
  • N3126 had the less strict rules that a copy constructor would not be implicitly declared if there is a user-declared move constructor, and that a copy assignment operator would not be implicitly declared if there is a user-declared move assignment operator. `unique_ptr` has both user-declared move constructor and move assignment operator, so I think the user-declared copy constructor and copy assignment operator wouldn't be necessary even when applying the N3126 rules. Not really important, but since the conventions used by the standard library classes might be interpreted as being best – Philipp Jan 24 '11 at 22:44
  • practices, it would be nice to know whether the explicitly declared copy constructor and copy assignment operator are intentional. – Philipp Jan 24 '11 at 22:45
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.

CashCow
  • 29,087
  • 4
  • 53
  • 86
2

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.

Puppy
  • 138,897
  • 33
  • 232
  • 446
  • 1
    I believe even if a class is not copyable, you want to define copy constructor and assignment operator (as deleted). So a movable resource-managing class should define all five, too. – Philipp Jan 24 '11 at 14:23
  • 1
    @Philipp, I strongly disagree, many classes don't support move semantics and it makes no sense to define two redundant functions just for some sense of aesthetics. Why should `std::complex` care about rvalue references? – Motti Jan 24 '11 at 15:25
  • @Motti: Why does it define regular copy semantics? Virtually all resources that can be copied can be moved. – Puppy Jan 24 '11 at 15:33
  • @Motti: Philipp said they should be defined *as deleted*! So you should explicitly adverse the fact that they don’t support the operation. – Konrad Rudolph Jan 24 '11 at 15:36
  • @Konrad this seems overly verbose to me, once a cctor is defined the mctor will not be defined (as I understand the current draft). Would you also define your default constructor as deleted for every class the defines a custom constructor? – Motti Jan 24 '11 at 15:51
  • @Motti: I don’t know the details of code-generated functions in C++0x. I understood Philipp’s comment as implying that if they are not explicitly defined as deleted, they would be auto-generated. Apparently that was a mistake. – Konrad Rudolph Jan 24 '11 at 16:57
  • @Motti, Konrad: if you don't declare copy constructor and copy assignment operator, they are always auto-generated, as in C++03. Of course you can define them any way you like (or not at all), but it seems to be the most idiomatic way to define them as deleted if the class is not copyable. That is what seems to be most natural (in contrast to declaring them as private), and is done by e.g. `unique_ptr`. In my first comment I didn't talk about non-movable classes at all. There may be examples for classes that can be copied but not moved, but I'm not aware of any. If the copy is possible and che – Philipp Jan 24 '11 at 18:03
  • ap, you can of course leave out the move constructor and assignment operator. But for many resource-managing classes, copies aren't cheap and sometimes not even possible. That's what I mean with "movable resource-management classes". – Philipp Jan 24 '11 at 18:05
  • Correction: I just read that a copy constructor or copy assignment operator is not generated if a move constructor or move assignment operator is declared, so that you indeed don't have to define copy constructor and copy assignment operator in that case. I've edited my answer accordingly. – Philipp Jan 24 '11 at 18:12