Summary Files Commits Branches @commit @diff @stats
path: root / src / teaching / oop-2025 / oop-notes / RuleOfFive.cpp
blob: c29afe235e7ee2b6aa1f3accc9f56402cb017920 (plain) (blame)
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
class X {
    Y* elements;
    unsigned elementsCount;

    void free() {
        delete[] elements;
    }
    void copyFrom(const X& other) {
        elementsCount = other.elementsCount;

        elements = new Y[elementsCount];
        for (unsigned i = 0; i < elementsCount; ++i)
            elements[i] = other.elements[i];
    }

public:
    X() {
        elements = nullptr;
        elementsCount = 0;
    }
    ~X() {
        free();
    }
    X(const X& other) {
        copyFrom(other);
    }
    X& operator=(const X& other) {
        if (this != &other) {
            free();
            copyFrom(other);
        }
        return *this;
    }

    X(X&& other) {
        elements = other.elements;
        elementsCount = other.elementsCount;

        other.elements = nullptr;
        other.elementsCount = 0;
    }
    X& operator=(X&& other) {
        if (this != &other) {
            free();

            elements = other.elements;
            elementsCount = other.elementsCount;

            other.elements = nullptr;
            other.elementsCount = 0;
        }
        return *this;
    }
};