Move assignment is a way to transfer resources (like memory, files, etc) from one object to another without copying them.
Example:
#include <iostream>
#include <vector>
// for std::move
#include <utility>
int main() {
std::vector<int> a = {1, 2, 3, 4};
std::vector<int> b;
// move assignment!
b = std::move(a);
// a is now empty
std::cout << "a.size() = " << a.size() << "\n";
// b has the data
std::cout << "b.size() = " << b.size() << "\n";
}
Output
a.size() = 0 b.size() = 4
Move Assignment Operator
It is a special function that lets an object take ownership of resources from another object without copying.
User-Defined Move Assignment Operator
The programmer can define the move assignment operator .
Example:
#include <iostream>
#include <cstring>
class MyString {
char* data;
public:
// Constructor
MyString(const char* str = "") {
data = new char[strlen(str) + 1];
strcpy(data, str);
}
// User-defined move assignment operator
MyString& operator=(MyString&& other) {
std::cout << "Move assignment called\n";
if (this != &other) {
// Free old memory
delete[] data;
// Steal the pointer
data = other.data;
// Set source to null
other.data = nullptr;
}
return *this;
}
// Destructor
~MyString() {
delete[] data;
}
void print() const {
if (data)
std::cout << data << "\n";
else
std::cout << "[empty]\n";
}
};
int main() {
MyString a("Hello");
MyString b("World");
b = std::move(a);
b.print();
a.print();
}
Output
Move assignment called Hello [empty]
Need of Move Assignment Operator
- Improves performance - Move assignment transfers resource instead of copying them, which is much faster, especially for large objects.
- Reduces memory usage - It avoids creating unnecessary duplicates in memory by reusing existing resources.
- Handles temporary objects efficiently - Move assignment allows objects to take ownership of data from temporary values without expensive copying.