Lesson 13 of 45 · C++
Lesson 20: Copy Constructor, Assignment Operator, Rule of Three/Five
Duration: 12 min
Lesson 13 of 45 · C++
Duration: 12 min
cpp\nclass Buffer {\n std::size_t size_;\n char* data_;\npublic:\n // Constructor\n explicit Buffer(std::size_t s) : size_(s), data_(new char[s]) {\n std::fill(data_, data_ + size_, 0);\n }\n // Destructor\n ~Buffer() { delete[] data_; }\n // Copy constructor\n Buffer(const Buffer& other) : size_(other.size_), data_(new char[other.size_]) {\n std::copy(other.data_, other.data_ + other.size_, data_);\n }\n // Copy‑assignment operator\n Buffer& operator=(const Buffer& other) {\n if (this != &other) {\n delete[] data_;\n size_ = other.size_;\n data_ = new char[size_];\n std::copy(other.data_, other.data_ + size_, data_);\n }\n return *this;\n }\n // Move constructor\n Buffer(Buffer&& other) noexcept : size_(other.size_), data_(other.data_) {\n other.size_ = 0;\n other.data_ = nullptr;\n }\n // Move‑assignment operator\n Buffer& operator=(Buffer&& other) noexcept {\n if (this != &other) {\n delete[] data_;\n size_ = other.size_;\n data_ = other.data_;\n other.size_ = 0;\n other.data_ = nullptr;\n }\n return *this;\n }\n // Simple accessor\n std::size_t size() const { return size_; }\n};\n\n\nBy handling copy and move explicitly, you avoid double‑deletes and enable efficient transfers.\n\n> Tip: If a class can be safely copied with the default behaviour, = default is preferable to writing boilerplate.\n\n---\n\n<Alert type="info">The Rule of Zero suggests preferring standard containers (std::vector, std::string) that already implement the rule of five for you.