When a class explicitly declares a copy operation (i.e., a copy constructor or copy assignment operator), move operations are not declared for the class. But when a class explicitly declares a move operation, the copy operations are declared as deleted. Why does this asymmetry exist? Why not just specify that if a move operation is declared, no copy operations will be declared? From what I can tell, there would not be any behavioral difference, and there would be no need for the asymmetric treatment of move and copy operations.
[For people who like citations of the standard, the lack of declaration of move operations for classes with copy operation declarations is specified in 12.8/9 and 12.8/20, and the deleted copy operations for classes with move operation declarations are specified in 12.8/7 and 12.8/18.]
When a class would be moved but for the fact that no move constructor is declared, the compiler falls back to copy constructor. In the same situation, if move constructor is declared as deleted, the program would be ill-formed. Thus, if move constructor were implicitly declared as deleted, a lot of reasonable code involving existing pre-C++11 classes would fail to compile. Things like myVector.push_back(MyClass())
This explains why move constructor cannot be implicitly declared deleted when copy constructor is defined. This leaves the question of why copy constructor is implicitly declared deleted when move constructor is defined.
I don't know the exact motivation of the committee, but I have a guess. If adding a move constructor to existing C++03-style class were to remove a (previously implicitly defined) copy constructor, then existing code using this class may change meaning in subtle ways, due to overload resolution picking unexpected overloads that used to be rejected as worse matches.
Consider:
struct C {
C(int) {}
operator int() { return 42; }
};
C a(1);
C b(a); // (1)
This is a legacy C++03 class. (1) invokes an (implicitly defined) copy constructor. C b((int)a); is also viable, but is a worse match.
Imagine that, for whatever reason, I decide to add an explicit move constructor to this class. If the presence of move constructor were to suppress the implicit declaration of copy constructor, then a seemingly unrelated piece of code at (1) would still compile, but silently change its meaning: it would now invoke operator int() and C(int). That would be bad.
On the other hand, if copy constructor is implicitly declared as deleted, then (1) would fail to compile, alerting me to the problem. I would examine the situation and decide whether I still want a default copy constructor; if so, I would add C(const C&)=default;
Why does this asymmetry exist?
Backward compatibility, and because the relationship between copying and moving is already asymmetrical. The definition of MoveConstructible is a special case of CopyConstructible, meaning that all CopyConstructible types are also MoveConstructible types. That's true because a copy constructor taking a reference-to-const will handle rvalues as well as lvalues.
A copyable type can be initialized from rvalues without a move constructor (it just might not be as efficient as it could be with a move constructor).
A copy constructor can also used to perform a "move" in implicitly-defined move constructors of derived classes when moving the base sub-object.
So a copy constructor can be seen as a "degenerate move constructor", so if a type has a copy constructor it doesn't strictly need a move constructor, it is already MoveConstructible, so simply not declaring the move constructor is acceptable.
The opposite is not true, a movable type is not necessarily copyable, e.g. move-only types. In those cases, making the copy constructor and assignment deleted provides better diagnostics than just not declaring them and getting errors about binding lvalues to rvalue references.
Why not just specify that if a move operation is declared, no copy operations will be declared?
Better diagnostics and more explicit semantics. "Defined as deleted" is the C++11 way to clearly say "this operation is not allowed", rather than just happening to be omitted by mistake or missing for some other reason.
The special case of "not declared" for move constructors and move assignment operators is unusual and is special because of the asymmetry described above, but special cases are usually best kept for a few narrow cases (it's worth noting here that "not declared" can also apply to the default constructor).
Also worth noting is that one of the paragraphs you refer to, [class.copy] p7, says (emphasis mine):
If the class definition does not explicitly declare a copy constructor, 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.
"The latter case" refers to the "otherwise, it is defined as defaulted" part. Paragraph 18 has similar wording for the copy assignment operator.
So the intention of the committee is that in some future version of C++ other types of special member function will also cause the copy constructor and copy assignment operator to be deleted. The reasoning is that if your class needs a user-defined destructor then the implicitly-defined copy behaviour is probably not going to do the right thing. That change hasn't been made for C++11 or C++14 for backward compatibility reasons, but the idea is that in some future version to prevent the copy constructor and copy assignment operator being deleted you will need to declare them explicitly and define them as defaulted.
So deleting copy constructors if they might not do the right thing is the general case, and "not declared" is a special case just for move constructors, because the copy constructor can provide the degenerate move anyway.
It is essentially to avoid migrated code to perform unexpected different actions.
Copy and move require a certain level of coherence, so C++11 -if you declare just one- suppress the other.
Consider this:
C a(1); //init
C b(a); //copy
C c(C(1)); //copy from temporary (03) or move(11).
Suppose you write this in C++03.
Suppose I compile it later in C++11.
If no ctor are declared, the default move does a copy (so the final behavior is the same as C++03).
If copy is declared, move is deleted, and sine C&& decays into C const& The third statement result in a copy from a temporary. This is still a C++03 identical behavior.
Now, if I'm adding later a move ctor, it means I'm changing the behavior of C (something you did not plan when defining C in C++03), and since a movable object does not need to be copyable (and vice versa), The compiler assumes that by making it movable, the dafault copy may be not anymore adequate. It's up to me to implementing it in coherence with the move or -if I found it adequate- restore the C(const C&)=default;
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
I am reading C++ primer 5 edition. until chapter 13 when talking about "move operations":
Unlike the copy operations, a move operation is never implicitly defined as a deleted function. However, if we explicitly ask the compiler to generate a move operation by using = default (§ 7.1.4, p. 264), and the compiler is unable to move all the members, then the move operation will be defined as deleted. With one important exception, the rules for when a synthesized move operation is defined as deleted are analogous to those for the copy operations (§ 13.1.6, p. 508):
Unlike the copy constructor, the move constructor is defined as deleted if the class has a member that defines its own copy constructor but does not also define a move constructor, or if the class has a member that doesn’t define its own copy operations and for which the compiler is unable to synthesize a move constructor. Similarly for move-assignment.
The move constructor or move-assignment operator is defined as deleted if the class has a member whose own move constructor or move-assignment operator is deleted or inaccessible.
Like the copy constructor, the move constructor is defined as deleted if the destructor is deleted or inaccessible.
Like the copy-assignment operator, the move-assignment operator is defined as deleted if the class has a const or reference member.
So I don't understand "unlike the copy operations, a move operation is never implicitly defined as a deleted function".
Does this mean copy operations are defined implicitly as deleted operations? if so when?
In other words please explain the difference between implicit move operations and their corresponding copy ones.
Does this mean copy operations are defined implicitly as deleted operations? if so when?
Yes.
When the members cannot be copied (e.g. they are of non-copyable types).
So I don't understand "unlike the copy operations, a move operation is never implicitly defined as a deleted function".
When the members can't be copied, the copy constructor is deleted.
When the members can't be moved, the move constructor is not deleted. Instead, it simply doesn't exist, so a copy is performed instead.
Unless the copy constructor was deleted! Then you just can't do anything.
If the move constructor were deleted, there would be an immediate compilation error, not an attempt to use the copy constructor instead.
In other words please explain the difference between implicit move operations and their corresponding copy ones.
The key here is the difference between not declaring something, and declaring it as deleted.
I don't know why the book's making such a big deal out of this. The difference is only interesting if it's interesting that the copy constructor gets implicitly deleted sometimes. And it's not particularly interesting that the copy constructor is deleted, because if it weren't, you still just wouldn't get a copy. There'd be no other constructor to fall back on. Well, I suppose, given some other implicit conversion sequences I suppose there could be, so that's a little interesting.
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