example2_move_assignment_operator.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
#include <iostream>
#include <utility>

class Resource {
private:
    int* data;
    size_t size;

public:
    Resource(size_t n = 0) : size(n), data(n ? new int[n]() : nullptr) {}

    ~Resource() {
        delete[] data;
    }

    // Copy assignment operator
    Resource& operator=(const Resource& other) {
        if (this != &other) {
            delete[] data;
            size = other.size;
            data = new int[size];
            std::copy(other.data, other.data + size, data);
        }
        return *this;
    }

    // Move assignment operator
    Resource& operator=(Resource&& other) noexcept {
        if (this != &other) {
            delete[] data;
            data = other.data;
            size = other.size;
            other.data = nullptr;
            other.size = 0;
        }
        return *this;
    }

    void print() const {
        for (size_t i = 0; i < size; ++i) {
            std::cout << data[i] << " ";
        }
        std::cout << std::endl;
    }
};

int main() {
    Resource r1(5);
    Resource r2;
    
    // Copy assignment
    r2 = r1;
    
    // Move assignment
    Resource r3;
    r3 = std::move(r1);
    
    r2.print();  // Output: 0 0 0 0 0
    r3.print();  // Output: 0 0 0 0 0
    r1.print();  // Output: (empty, as r1 has been moved from)
    
    return 0;
}
Back to assignment_operator