Lesson 2 of 5
Rule of 0, 3 & 5 - The Complete Rules
**Rule of 0**: Classes that don't manage resources directly should declare NONE of the special member functions - let the compiler generate all six. If all members are value types or smart pointers, the generated copy/move/destructor do the right thing. **Rule of 3** (pre-C++11): if you declare any of destructor/copy ctor/copy assign, declare all three. **Rule of 5** (C++11+): extend Rule of 3 - also declare (or delete) the move constructor and move assignment for completeness and efficiency.
Rule of 0/3/5 - Pattern Reference with =default & =delete
#include <iostream>
#include <string>
#include <memory>
#include <algorithm>
// ── RULE OF 0 - the ideal pattern ────────────────────────────
// No resource management → no special functions declared.
// All members are RAII types → generated specials work correctly.
class UserProfile {
std::string name_; // RAII - handles copy/move
std::vector<std::string> tags_; // RAII
std::unique_ptr<std::string> bio_; // RAII - move only (no copy)
// Rule of 0: declare nothing. Generated specials:
// - Default ctor: default-constructs all members (OK)
// - Copy ctor: copies name_, tags_; bio_ is DELETED → UserProfile not copyable
// (unless we either delete copy or implement deep copy)
// - Move ctor: moves all members (O(1))
public:
UserProfile() = default;
UserProfile(std::string name) : name_(std::move(name)) {}
// All specials: compiler-generated correctly
};
// ── RULE OF 5 - resource-managing class ──────────────────────
class DynArray {
int* data_;
size_t size_;
public:
// 1. Constructor
explicit DynArray(size_t n)
: data_(new int[n]()), size_(n) {
std::cout << "DynArray(" << n << ")
";
}
// 2. Destructor
~DynArray() noexcept {
delete[] data_;
std::cout << "~DynArray(" << size_ << ")
";
}
// 3. Copy constructor - deep copy
DynArray(const DynArray& other)
: data_(new int[other.size_]), size_(other.size_) {
std::copy(other.data_, other.data_ + size_, data_);
std::cout << "DynArray(copy)
";
}
// 4. Copy assignment - copy-and-swap idiom
DynArray& operator=(DynArray other) noexcept { // by value = copy already done
std::swap(data_, other.data_);
std::swap(size_, other.size_);
return *this;
// other (old data) destroyed here
}
// 5. Move constructor - steal resources
DynArray(DynArray&& other) noexcept
: data_(other.data_), size_(other.size_) {
other.data_ = nullptr;
other.size_ = 0;
std::cout << "DynArray(move)
";
}
// 6. Move assignment
DynArray& operator=(DynArray&& other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
size_ = other.size_;
other.data_ = nullptr;
other.size_ = 0;
}
return *this;
}
size_t size() const noexcept { return size_; }
int& operator[](size_t i) { return data_[i]; }
const int& operator[](size_t i) const { return data_[i]; }
};
// ── = delete - disable specific operations ────────────────────
class Singleton {
static Singleton instance_;
Singleton() = default;
public:
static Singleton& get() { return instance_; }
Singleton(const Singleton&) = delete; // no copy
Singleton& operator=(const Singleton&) = delete; // no copy-assign
Singleton(Singleton&&) = delete; // no move
Singleton& operator=(Singleton&&) = delete; // no move-assign
void work() { std::cout << "Singleton::work()
"; }
};
Singleton Singleton::instance_;
int main() {
std::cout << "--- Rule of 5 demo ---
";
DynArray a(5);
a[0] = 10; a[1] = 20;
DynArray b = a; // COPY ctor
DynArray c = std::move(a); // MOVE ctor - a is empty after
DynArray d(3);
d = b; // COPY assign (copy-and-swap)
d = std::move(c); // MOVE assign
std::cout << "b[0]=" << b[0] << " d[0]=" << d[0] << "
"; // 10 10
Singleton::get().work();
// Singleton s2 = Singleton::get(); ← compile error: deleted
return 0;
}Common Mistakes
- Copy-and-swap combined copy ctor + copy assign - using a single `operator=(DynArray other)` (by value) handles both copy and move assignment: if called with an lvalue, the parameter is copy-constructed; if called with an rvalue (`std::move(x)`), it's move-constructed. This is elegant but slightly less efficient than separate copy/move assignments.
- Not marking move constructor `noexcept` - vector reallocation checks for noexcept. Without it, vector uses copy during emplace_back/push_back growth - O(n) instead of O(n) moves. Always mark move ctors `noexcept` for RAII classes that manage raw resources.
- `= default` in implementation file vs header - `DynArray(const DynArray&) = default;` in a header is fine. If the defaulted function has a complex body (due to member types), defining it in the .cpp with `= default` can improve compile times.
Tip
Tip
Practice Rule of 0 3 5 The Complete Rules in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Managing copy and move operations when custom resource handles are owned
Practice Task
Note
Practice Task - (1) Write a working example of Rule of 0 3 5 The Complete Rules from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Rule of 0 3 5 The Complete Rules is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- **Rule of 0**: Classes that don't manage resources directly should declare NONE of the special member functions - let the compiler generate all six.
- Copy-and-swap combined copy ctor + copy assign - using a single `operator=(DynArray other)` (by value) handles both copy and move assignment: if called with an lvalue, the parameter is copy-constructed; if called with an rvalue (`std::move(x)`), it's move-constructed. This is elegant but slightly less efficient than separate copy/move assignments.
- Not marking move constructor `noexcept` - vector reallocation checks for noexcept. Without it, vector uses copy during emplace_back/push_back growth - O(n) instead of O(n) moves. Always mark move ctors `noexcept` for RAII classes that manage raw resources.
- `= default` in implementation file vs header - `DynArray(const DynArray&) = default;` in a header is fine. If the defaulted function has a complex body (due to member types), defining it in the .cpp with `= default` can improve compile times.
Finished this lesson?