Learning Hub Search Ctrl K

Legacy C++ › 3. Classes and Object-Oriented Programming

RAII and the Rule of Three

Tie a resource's lifetime to an object's lifetime, and know which special members you must write together.

intermediate #raii#constructors#destructors#copying

Explanation

RAII (Resource Acquisition Is Initialization): acquire a resource in a constructor and release it in the destructor. Because destructors run during stack unwinding, the resource is released even when an exception is thrown.

Rule of Three: if a class needs a user-defined destructor, copy constructor, or copy assignment operator, it almost certainly needs all three. The usual reason is that it owns a resource, and the compiler-generated copy would copy only the pointer (a shallow copy), leading to a double delete.

Example

#include <cstring>
#include <iostream>

class Buffer {
    char*       data_;
    std::size_t size_;
public:
    explicit Buffer(std::size_t n) : data_(new char[n]), size_(n) { std::memset(data_, 0, n); }

    ~Buffer() { delete[] data_; }                               // 1. destructor

    Buffer(const Buffer& o) : data_(new char[o.size_]), size_(o.size_) {   // 2. copy ctor
        std::memcpy(data_, o.data_, size_);
    }

    Buffer& operator=(const Buffer& o) {                        // 3. copy assignment
        if (this != &o) {
            char* fresh = new char[o.size_];
            std::memcpy(fresh, o.data_, o.size_);
            delete[] data_;
            data_ = fresh;
            size_ = o.size_;
        }
        return *this;
    }

    std::size_t size() const { return size_; }
};

int main() {
    Buffer a(16);
    Buffer b = a;       // deep copy, safe
    b = a;              // deep copy, safe
    std::cout << b.size() << "\n";
    return 0;
}

Common pitfalls

  • Writing only the destructor: copies share one buffer and it is freed twice.
  • Self-assignment (a = a) when you delete before copying.
  • Not exception-safe assignment: allocate the new storage before releasing the old, as above.

Legacy vs modern

C++11 extends this to the Rule of Five (adding move constructor and move assignment), and the Rule of Zero says: use std::vector / smart pointers and write none of them. See Move Semantics and unique_ptr.

Exercises

1. Why must the copy constructor take a const reference?

A by-value parameter would itself need the copy constructor to initialize, causing infinite recursion. const lets you copy from temporaries and const objects.