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

int main() {
    MyClass obj1("Hello, World!");
    MyClass obj2(std::move(obj1));  // obj1 is cast to an rvalue using std::move

    std::cout << "obj2.data: " << obj2.data << std::endl;

    return 0;
}
Back to rvalue