example2_invoke_move_in_assignment.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>

class MyClass {
public:
    std::string data;

    // Constructor
    MyClass(const std::string& str) : data(str) {
        std::cout << "Constructed\n";
    }

    // Move Constructor
    MyClass(MyClass&& other) noexcept : data(std::move(other.data)) {
        std::cout << "Move Constructed\n";
    }

    // Move Assignment Operator
    MyClass& operator=(MyClass&& other) noexcept {
        if (this != &other) {
            data = std::move(other.data);  // Move the data
            std::cout << "Move Assigned\n";
        }
        return *this;
    }

    // Copy Constructor
    MyClass(const MyClass& other) : data(other.data) {
        std::cout << "Copy Constructed\n";
    }

    // Copy Assignment Operator
    MyClass& operator=(const MyClass& other) {
        if (this != &other) {
            data = other.data;
            std::cout << "Copy Assigned\n";
        }
        return *this;
    }
};

int main() {
    MyClass obj1("Hello, World!");
    MyClass obj2("Goodbye!");

    obj2 = std::move(obj1);  // Move assignment is called

    std::cout << "obj1.data: " << obj1.data << "\n";  // obj1 is in a valid but unspecified state
    std::cout << "obj2.data: " << obj2.data << "\n";

    return 0;
}
Back to std_move