Lesson 20 of 45
C++Lesson 20: Copy Constructor, Assignment Operator, Rule of Three/Five
12 min
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 20 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
When a class manages a resource (e.g., dynamic memory), you must define how copying and moving work. The Rule of Three states that if you define any of destructor, copy constructor, or copy‑assignment operator, you should usually define all three. C++11 added move semantics, extending the rule to Five (add move constructor and move‑assignment operator).
class Buffer {
std::size_t size_;
char* data_;
public:
// Constructor
explicit Buffer(std::size_t s) : size_(s), data_(new char[s]) {
std::fill(data_, data_ + size_, 0);
}
// Destructor
~Buffer() { delete[] data_; }
// Copy constructor
Buffer(const Buffer& other) : size_(other.size_), data_(new char[other.size_]) {
std::copy(other.data_, other.data_ + other.size_, data_);
}
// Copy‑assignment operator
Buffer& operator=(const Buffer& other) {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = new char[size_];
std::copy(other.data_, other.data_ + size_, data_);
}
return *this;
}
// Move constructor
Buffer(Buffer&& other) noexcept : size_(other.size_), data_(other.data_) {
other.size_ = 0;
other.data_ = nullptr;
}
// Move‑assignment operator
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = other.data_;
other.size_ = 0;
other.data_ = nullptr;
}
return *this;
}
// Simple accessor
std::size_t size() const { return size_; }
};
By handling copy and move explicitly, you avoid double‑deletes and enable efficient transfers.
Tip: If a class can be safely copied with the default behaviour,
= defaultis preferable to writing boilerplate.
<Alert type="info">The Rule of Zero suggests preferring standard containers (std::vector, std::string) that already implement the rule of five for you.