I am reading about the std::move, move constructor and move assignment operator. To be honest, all I got now is confusion. Now I have a class:
class A{
public:
B
is the name of an object. Once a reference has been bound, it names an object. The distinction "rvalue reference", "lvalue reference" and "named object" only applies to how the name can be bound before you got this far.B.key
is the name of a variable in the object which was supplied as argument to this function call.
The line A.key = std::move(B.key)
invokes the built-in definition of assignment for an int
(this is a simple assignment, not a function call), which is just a copy. So B.key
retains its value.
For A(B())
to compile, B
must be a typename which you haven't defined yet. (Did you mean A(A())
? If so, then the answer is "Yes").
See 2
Use std::move(Z.foo)
whenever you want to move out of Z.foo
instead of copying from Z.foo
.
You have to understand that std::move
does not move anything, but "marks" its argument to be a rvalue reference. Technically, it converts the type to a rvalue reference. Then, the rvalue reference it's being moved by the corresponding move constructor or move assignment operator. For objects that contain only members with trivial move ctors/assignment operators, the move ctor/assignment operator is trivial and simply copies. In general, the move ctor/assignment operator of the object calls the move ctor/assignment operator of all its members.
So, whenever you write
int x = 10; int y = std::move(x);
on the right hand side of the assignment y = std::move(x)
, you have a rvalue reference of type int&&
. However, int
does not have a non-trivial move ctor, and the rvalue is simply copied into y
, nothing is changed in x
.
On the other hand,
string s = "some string"; string moved_s = std::move(s); // here we tell the compiler that we can "steal" the resource of s
is different. The move constructor of moved_s
kicks in, and "steals" (i.e. swaps internal pointers etc) the resource of s
, because the latter is a rvalue reference. At the end, s
will not contain any element.