example1_invoke_move_constructor.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
#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";
    }

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

int main() {
    MyClass obj1("Hello, World!");
    MyClass obj2 = std::move(obj1);  // Move constructor 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