example2_move_with_stl_containers.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <vector>

class MyClass {
public:
    int* data;
    std::size_t size;

    // Constructor
    MyClass(std::size_t s) : size(s) {
        data = new int[s];
        std::cout << "Constructed with size: " << size << std::endl;
    }

    // Destructor
    ~MyClass() {
        delete[] data;
        std::cout << "Destroyed" << std::endl;
    }

    // Copy Constructor
    MyClass(const MyClass& other) : size(other.size) {
        data = new int[size];
        std::copy(other.data, other.data + size, data);
        std::cout << "Copy Constructed" << std::endl;
    }

    // Move Constructor
    MyClass(MyClass&& other) noexcept : data(nullptr), size(0) {
        data = other.data;
        size = other.size;
        other.data = nullptr;
        other.size = 0;
        std::cout << "Move Constructed" << std::endl;
    }

    // Copy Assignment Operator
    MyClass& operator=(const MyClass& other) {
        if (this == &other)
            return *this;

        delete[] data;
        size = other.size;
        data = new int[size];
        std::copy(other.data, other.data + size, data);
        std::cout << "Copy Assigned" << std::endl;
        return *this;
    }

    // Move Assignment Operator
    MyClass& operator=(MyClass&& other) noexcept {
        if (this == &other)
            return *this;

        delete[] data;

        data = other.data;
        size = other.size;
        other.data = nullptr;
        other.size = 0;
        std::cout << "Move Assigned" << std::endl;
        return *this;
    }
};

int main() {
    std::vector<MyClass> vec;
    vec.reserve(2);

    MyClass obj1(10);
    vec.push_back(std::move(obj1));  // Uses move constructor

    MyClass obj2(20);
    vec.push_back(std::move(obj2));  // Uses move constructor

    return 0;
}
Back to move_semantics