What does it mean move operations are never defined as deleted functions - c++

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.

Related

What does it mean: "a move operation is never implicitly defined as a deleted function" in C++Primer 5th edition?

I am reading "C++ Primer", 5th edition. And I can not understand the following passage. It comes from page 538~539.
Unlike the copy operations, a move operation is never implicitly defined as a deleted function.
Never? But aren't all the definitions mentioned later implicit?
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.

Do I have to write a copy constructor when writing a move constructor in C++?

I know about the rule of five which states that if you implement a destructor, you should most likely also implement a copy constructor, copy assignment operator, a move constructor and a move assignment operator.
However if I implement a move operator, do I absolutely have to implement a copy counterpart, or is it just best practice?
The "Rule of Zero" may be applicable to your situation. Why are you providing a move constructor or move assignment operator in the first place? Is it because your class represents unique ownership of some resource? If so, it may be better to encapsulate ownership of that resource in a unique_ptr member or something similar. Then, you don't need to write the move constructor and move assignment operator anymore. The compiler will generate them automatically, which will move the unique_ptr member and thus transfer ownership. The compiler will also ensure that the class is not copyable.
OK, but let's say that for some reason the Rule of Zero is not appropriate to your class. What will happen if you declare only a move constructor? Then, the compiler will implicitly disable copying for your class, which will mean that objects of your class type can only be initialized from rvalues of the same type, and not from lvalues. The Rule of Five tells you that it is better to be explicit about this situation instead of leaving it to the reader to guess what the compiler is doing. So, it is best practice (but not required) to define the copy constructor as = delete;.

Why does destructor disable generation of implicit move methods?

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.

Generated copy and move operators?

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

Why are copy operations deleted when move operations are declared?

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;