C++ Constructors, Destructors, Rule of 5 & RAII Masterclass

โšก Modern C++ (C++17 / C++20 / C++23) ๐ŸŸข Lesson 10 ๐Ÿ“‚ Phase 10: Constructors, Destructors & RAII ๐Ÿ“… 2026 Master Edition
๐Ÿ“Œ Covered in this in-depth guide: Constructors & Destructors ยท Member Initializer Lists ยท Copy vs Move Semantics ยท Rule of Zero / Three / Five ยท RAII Resource Management ยท std::move

Welcome to Phase 10 (Chapter 10): C++ Constructors, Destructors, Rule of 5 & RAII Masterclass! Object lifecycle management is the core strength of C++. In this guide, you will master constructors, copy/move semantics, Rule of Zero / Three / Five, and RAII (Resource Acquisition Is Initialization).

1The Rule of Zero, Three, and Five Matrix
Rule NameWhen It AppliesSpecial Member Functions to Implement
Rule of ZeroClasses using RAII members (vectors, strings, smart pointers).None! Rely on compiler-generated defaults. (Preferred modern style!)
Rule of Three (C++98)Classes managing raw heap memory or file handles.1. Destructor
2. Copy Constructor
3. Copy Assignment Operator
Rule of Five (C++11)Classes managing raw resources requiring move optimization.1. Destructor
2. Copy Constructor
3. Copy Assignment
4. Move Constructor
5. Move Assignment
2RAII (Resource Acquisition Is Initialization) Paradigm
RAII Execution Lifecycle: Scope Entry โ”€โ”€โ–บ Constructor executes โ”€โ”€โ–บ Acquires Resource (Heap memory, File handle, Mutex lock) โ”‚ โ–ผ [Normal Execution OR Exception Thrown] โ”‚ Scope Exit โ”€โ”€โ–บ Destructor executes โ”€โ”€โ–บ Automatically Releases Resource! (Zero Leaks!)

RAII guarantees resource cleanup even if exceptions are thrown during function execution!

3Complete RAII Class Implementation
C++ โ€” Exception-Safe RAII Resource Managerโ–ถ Run Code in C++ Compiler
#include <iostream>
#include <utility> // for std::move

class IntBuffer {
private:
    int* data;
    size_t size;

public:
    // 1. Parameterized Constructor (Resource Acquisition)
    explicit IntBuffer(size_t bufferSize)
        : data(new int[bufferSize]{}), size(bufferSize) {
        std::cout << "[RAII] Allocated buffer of " << size << " ints\n";
    }

    // 2. Destructor (Automatic Resource Release)
    ~IntBuffer() {
        delete[] data;
        std::cout << "[RAII] Freed buffer memory safely.\n";
    }

    // 3. Copy Constructor (Deep Copy)
    IntBuffer(const IntBuffer& other) : data(new int[other.size]), size(other.size) {
        for (size_t i = 0; i < size; i++) data[i] = other.data[i];
        std::cout << "[Rule of 5] Deep Copy Constructor called.\n";
    }

    // 4. Move Constructor (Resource Transfer - C++11)
    IntBuffer(IntBuffer&& other) noexcept : data(other.data), size(other.size) {
        other.data = nullptr;
        other.size = 0;
        std::cout << "[Rule of 5] Fast Move Constructor called.\n";
    }
};

int main() {
    {
        IntBuffer buf1(100); // Resource acquired
        IntBuffer buf2 = std::move(buf1); // Fast move, zero copy overhead!
    } // Scope ends: Destructor automatically called, memory freed!

    return 0;
}
4Technical FAQs

Q1: What is RAII in C++?

Resource Acquisition Is Initialization: A design pattern where resource allocation happens in the constructor and automatic deallocation happens in the destructor when the object goes out of scope.

Q2: Why prefer Rule of Zero in Modern C++?

By using standard containers (`std::vector`, `std::string`, `std::unique_ptr`) as member variables, the compiler automatically generates correct copy, move, and destruction logic without custom code.

Q3: What is the purpose of std::move?

std::move(x) casts an lvalue to an rvalue reference (x&&), enabling fast move construction by stealing resources instead of making deep copies.

Q4: Why mark move operations noexcept?

Standard library containers like std::vector will only use fast move constructors during reallocation if marked noexcept for exception safety guarantees.

Q5: What is constructor delegation?

A constructor calling another constructor of the same class in its member initializer list to reuse initialization code (C++11).