In C++, move constructors and move assignment operators are special member functions that allow the efficient transfer of resources from one object to another, particularly when dealing with dynamic memory or other resource-intensive operations. This is particularly useful for optimizing performance while avoiding unnecessary deep copies.
A move constructor allows you to create a new object using resources from an existing object. It is defined by taking an rvalue reference to the object you wish to "move" from.
The move assignment operator makes it possible to transfer resources from one existing object to another. It also takes an rvalue reference as its parameter.
// Example of Move Constructor and Move Assignment Operator in C++
#include
#include // for std::move
class MyClass {
public:
int* data;
size_t size;
// Constructor
MyClass(size_t s) : size(s), data(new int[s]) {
std::cout << "Constructor called\n";
}
// Move Constructor
MyClass(MyClass&& other) noexcept : size(other.size), data(other.data) {
other.size = 0;
other.data = nullptr;
std::cout << "Move Constructor called\n";
}
// Move Assignment Operator
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
delete[] data; // Clean up existing resource
size = other.size;
data = other.data;
other.size = 0;
other.data = nullptr;
std::cout << "Move Assignment Operator called\n";
}
return *this;
}
// Destructor
~MyClass() {
delete[] data;
std::cout << "Destructor called\n";
}
};
int main() {
MyClass obj1(10); // Create an object
MyClass obj2(std::move(obj1)); // Move obj1 to obj2 via move constructor
MyClass obj3(5);
obj3 = std::move(obj2); // Move obj2 to obj3 via move assignment
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?