diff options
1 files changed, 54 insertions, 0 deletions
| -rw-r--r-- | src/teaching/oop-2025/oop-notes/RuleOfFive.cpp | 54 |
diff --git a/src/teaching/oop-2025/oop-notes/RuleOfFive.cpp b/src/teaching/oop-2025/oop-notes/RuleOfFive.cpp new file mode 100644 index 0000000..c29afe2 --- /dev/null +++ b/src/teaching/oop-2025/oop-notes/RuleOfFive.cpp @@ -0,0 +1,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; + } +}; |