How do I implement move constructors and move assignment in C++?

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.

Move Constructor

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.

Move Assignment Operator

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


// 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;
}

Move Constructor Move Assignment Operator C++ Performance Optimization Resource Management