+ 1
c++ move assignment operator
So basically, I know about copy constructor, copy assignment and move constructor, but what is move assignment operator? What are the advantages of using it or in which scenario to use?
1 Answer
+ 2
OK you already know:
Copy constructor â makes a copy of an object.
Copy assignment operator â assigns one object to another via copying.
Move constructor â transfers resources from a temporary (rvalue) to a new object.
The missing piece is:
Move Assignment Operator:
The move assignment operator allows you to transfer resources from one object to another that already exists (unlike move constructor, which creates a new object). Its signature typically looks like:
class MyClass {
public:
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
// Release current resources
delete[] data;
// Steal resources from 'other'
data = other.data;
size = other.size;
// Leave 'other' in a valid state
other.data = nullptr;
other.size = 0;
}
return *this;
}
private:
int* data;
size_t size;
};
When is it used?
It is called when an existing object is assigned a temporary object (rvalue). For example:
MyClass a, b;
b = MyClass(1000); // Move assignment!
Here, MyClass(1000) is a temporary. Instead of copying its resources (which is expensive), the move assignment steals them.
Advantages:
Performance: Avoids deep copy of resources (like dynamic arrays, file handles, sockets). Just transfers pointers or handles â very fast.
Memory efficiency: No unnecessary allocations or copies. Old resources are properly released.
Enables modern C++ patterns: Works well with STL containers like std::vector or std::string. Makes code work efficiently with temporaries, return values, and rvalue references.
Example
std::vector<int> v1 = {1,2,3};
std::vector<int> v2;
v2 = std::move(v1); // Move assignment
v2 takes ownership of v1âs memory. v1 becomes empty but valid. No copying of elements â faster than copy assignment.