I was trying to understand what the rule of zero says by reading this blog. IMO, it says if you declare your own destructor then don't forget to make the move constructor and move assignment as default.
Example:
class Widget {
public:
~Widget(); // temporary destructor
... // no copy or move functions
};
"The addition of the destructor has the side effect of disabling
generation of the move functions, but because Widget is copyable, all
the code that used to generate moves will now generate copies. In
other words, adding a destructor to the class has caused
presumably-efficient moves to be silently replaced with
presumably-less-efficient copies".
The above text by Scott Meyers, inside the quotes raise some questions in my mind:
Why declaring destructor hides the move semantics?
Is declaring/definig destructor only hides the move semantics or copy
constructor and copy assignment as well hides the move semantics?
"The Rule of Zero" is in fact about something else than what special member functions are generated and when. It is about a certain attitude to class design. It encourages you to answer a question:
Does my class manage resources?
If so, each resource should be moved to its dedicated class, so that your classes only manage resources (and do nothing else) or only accumulate other classes and/or perform same logical tasks (but do not manage resources).
It is a special case of a more general Single Responsibility Principle.
When you apply it, you will immediately see that for resource-managing classes you will have to define manually move constructor, move assignment and destructor (rarely will you need the copy operations). And for the non-resource classes, you do not need to (and in fact you probably shouldn't) declare any of: move ctor/assignment, copy ctor/assignment, destructor.
Hence the "zero" in the name: when you separate classes to resource-managing and others, in the "others" you need to provide zero special member functions (they will be correctly auto-generated.
There are rules in C++ what definition (of a special member function) inhibits what other definitions, but they only distract you from understanding the core of the Rule of Zero.
For more information, see:
https://akrzemi1.wordpress.com/2015/09/08/special-member-functions/
https://akrzemi1.wordpress.com/2015/09/11/declaring-the-move-constructor/
Almost always, if you have a destructor (that "does something"), you should follow the "rule of three", which then becomes "rule of five" if you want move semantics.
If your destructor is empty, then it's not needed. So the implication is that a non-empty destructor (because you wouldn't have one if it's not needed!), then you also need to do the same thing in copy and assignment operations, and presumably, move construction and move assignment will need to "do something", and not just transfer the actual content across.
Of course, there may be cases where this is not true, but the compiler takes the approach of "let's only apply the automatically generated move functions if the destructor is empty", because that is the "safe" approach.
is declaring/defining Dtor only hide the move semantics or copy
ctor/copy assignment as well hide the move semantics?
If no user-defined move constructors are provided for a class all of the following is true:
there are no user-declared copy constructors
there are no user-declared copy assignment operators
there are no user-declared move assignment operators
there are no user-declared destructors
then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).
Thus, yes declaring a copy constructor or an assignment operator hides implicitly declared move constructor as well.
First I would say Mats Petersson's answer is better than the accepted one as it mentions the rationale.
Second, as a supplement, I want to elaborate a bit more.
The behavior of implicitly-declared (or defaulted) move ctor
From c++draft:
The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members.
The condition when compiler implicitly declares a move ctor
From cppreference:
If no user-defined move constructors are provided for a class all of
the following is true:
there are no user-declared copy constructors
there are no user-declared copy assignment operators
there are no user-declared move assignment operators
there are no user-declared destructors
then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).
Why dtor(and many others) prevents implicitly-declared move ctor?
If we look at the above conditions, not only user-declared destructor prevents implicitly-declared move ctor, user-declared copy constructor, user-declared copy assignment operator and user-declared move assignment operator all has the same prevention effect.
The rationale, as Mats Petersson has pointed out, is that:
If the compiler thinks you might need to do something other than memberwise move in move operation, then it is not safe to assume you don't need it.
When there are user-declared destructors, which means there's some clean up work to do, then you probably want to do it with the moved-from object.
When there are user-declared move assignment operators, since it's also "moving" resources, you probably want to do the same in move ctor.
When there are user-declared copy constructors or copy assignment operators, this is the most interesting case. We know that move semantics allows us to keep value semantics while gaining performance optimization, and that move will "fall back" to copy when move ctor is not provided. In some way, move can been seen as the "optimized copy". Therefore, if the copy operation requires us to do something, it is likely that similar work is also needed in move operation.
Since in the above conditions, something other than memberwise move might needs to be done, the compiler will not assume you don't need it, and thus won't implicitly declare a move ctor.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
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?
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.
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.
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.
Copy constructor
Assignment operator
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.
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).
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.
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.
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.
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.
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
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
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?
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.
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.
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.
Copy constructor
Assignment operator
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.
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).
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.
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.
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.
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.
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
Currently I read the book Effective Modern C++ from Scott Meyers, and now I'm at: Item 17: Understand special member function generation.
My misunderstanding comes from the following part (rationale):
The two copy operations are independent: declaring one doesn’t prevent compilers from generating the other. So if you declare a copy constructor, but no copy assignment operator, then write code that requires copy assignment, compilers will generate the copy assignment operator for you. Similarly, if you declare a copy assignment operator, but no copy constructor, yet your code requires copy construction, compilers will generate the copy constructor for you. That was true in C++98, and it’s still true in C++11.
The two move operations are not independent. If you declare either, that prevents compilers from generating the other. The rationale is that if you declare, say, a move constructor for your class, you’re indicating that there’s something about how move construction should be implemented that’s different from the default memberwise move that compilers would generate. And if there’s something wrong with memberwise move construction, there’d probably be something wrong with memberwise move assignment, too. So declaring a move constructor prevents a move assignment operator from being generated, and declaring a move assignment operator prevents compilers from generating a move constructor.
I think the rationale part could be applied to the copy constructor and copy assignment operator pair also, couldn't it ? So if I declare a copy constructor I indicate with it that the default memberwise copy is not adequate for me. And if I say this than probably the copy assignment operator should be user defined also.
I think it's a great book, but at this point this rationale is not clear for me. Please help and explain this for me. Thanks.
I think the rationale part could be applied to the copy constructor and copy assignment operator pair also, couldn't it ?
Absolutely. The standard agrees with you. In [class.copy]:
If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly.
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy
constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if
the class has a user-declared copy assignment operator or a user-declared destructor.
And:
If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. If
the class definition declares a move constructor or move assignment operator, the implicitly declared copy
assignment operator is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is
deprecated if the class has a user-declared copy constructor or a user-declared destructor.
Of course there's probably a lot of existing code that would break if the "latter cases" in question were done away with immediately, which is why the Standard moved first to deprecation and will only remove them at some arbitrarily distant point in the future.
Then again, even long-deprecated-and-since-removed features have a way of hanging around long past their welcome. Like char * s = "MyString";
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
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?
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.
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.
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.
Copy constructor
Assignment operator
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.
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).
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.
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.
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.
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.
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
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
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?
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.
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.
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.
Copy constructor
Assignment operator
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.
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).
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.
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.
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.
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.
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