As many other posts explain, declaring one variable as an rvalue reference does not guarantee that it will call the move assignment operator, only using std::move
(that is, casting to that same rvalue reference) will do it. For example:
struct A
{
A& operator=(A&& l_other) { std::cout << "move" << std::endl; }
A& operator=(A& l_other) { std::cout << "copy" << std::endl; }
};
A a;
// does not print anything, compiler does nothing here!
A&& b = std::move(a);
// prints "copy", not "move"
a = b;
// prints "move", but needs std::move()
a = std::move(b);
Seems that defining b
as A&&
does not move anything in that moment. After that, a = b
does not move b
automatically, even if right part is defined as A&&
, as other posts explain. We need to explicitly call std::move(b)
to move b
.
My question is, what's the utility of defining a variable as A&&
? I could perfectly define it as A&
and move it exactly the same.