example2_move_constructor_with_xvalues.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
#include <iostream>
#include <string>
#include <utility>  // For std::move

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!");
    //GE std::cout << "obj1.data: " << obj1.data << std::endl;   // data is present

    MyClass obj2(std::move(obj1));  // 'std::move(obj1)' produces an xvalue

    std::cout << "obj2.data: " << obj2.data << std::endl;
    //GE std::cout << "obj1.data: " << obj1.data << std::endl;  // data is gone

    return 0;
}
Back to xvalue