Move assignment operator is invoked when we declare an object and then try to assign an rvalue reference to it.
This is done via the move assignment operator.
The signature of the move assignment operator is:
MyClass& operator=(MyClass&& otherobject).
To define a user-defined move assignment operator inside a class we use:
class MyClass { public: MyClass& operator=(MyClass&& otherobject) { // implement the copy logic here return *this; } };
As with any assignment operator overloading, we must return a dereferenced this pointer at the end.
To define a move assignment operator outside the class, we use:
class MyClass //w w w . j av a2 s . c om { public: MyClass& operator=(const MyClass& rhs); }; MyClass& MyClass::operator=(const MyClass& rhs) { // implement the copy logic here return *this; }
Move assignment operator example adapted from a move constructor example would be:
#include <iostream> #include <string> class MyClass /*from www .j a v a 2 s.c o m*/ { private: int x; std::string s; public: MyClass(int xx, std::string ss) // user provided constructor : x{ xx }, s{ ss } {} MyClass& operator=(MyClass&& otherobject) // move assignment operator { x = std::move(otherobject.x); s = std::move(otherobject.s); return *this; } }; int main() { MyClass o1{ 123, "This is currently in object 1." }; MyClass o2{ 456, "This is currently in object 2." }; o2 = std::move(o1); // move assignment operator invoked std::cout << "Move assignment operator used."; }
Here we defined two objects called o1 and o2.
Then we try to move the data from object o1 to o2 by assigning an rvalue reference (of object o1) using the std::move(o1) expression to object o2.
This invokes the move assignment operator in our object o2.
The move assignment operator implementation itself uses the std::move()
function to cast each data member to an rvalue reference.