C++ · Module 8 · Lesson 41 min read

Destructors & RAII

Destructor

perl
class FileLogger {
public:
    ~FileLogger() { /* cleanup */ }
};
  • Name: ~ + class name; no parameters, no return type
  • Only one destructor per class
  • Runs automatically when the object's lifetime ends:
    • a local object goes out of scope
    • delete is called on a heap object
    • the program ends (for globals/statics)
    • a containing object is destroyed

Order of destruction

Objects are destroyed in the reverse order of construction (last created, first destroyed). Members are destroyed after the destructor body, in reverse declaration order.

RAII: Resource Acquisition Is Initialization ✅

  1. Acquire a resource in the constructor (memory, file, lock, network connection)
  2. Release it in the destructor
  3. Because destructors always run when scope ends — even if an exception is thrown or the function returns early — the resource can never leak

RAII in the standard library

ClassResource
std::vector, std::stringheap memory
std::unique_ptr, std::shared_ptrheap objects
std::ifstream, std::ofstreamopen files
std::lock_guardmutex locks
std::jthreadthreads (joins automatically)

Rules for destructors

  • Don't throw exceptions from destructors (they're noexcept by default)
  • If a class owns a raw resource, also think about copying (Rule of Three/Five, Unit 10)
  • Base classes used polymorphically need a virtual destructor (Unit 9)

Compare with other languages

Java/C#/Python use garbage collection plus finally/using/with for cleanup. In C++, the destructor is the cleanup, and it runs at a predictable time.

Example

C++
#include <iostream>
#include <stdexcept>
#include <string>

class Timer {                                   // RAII: reports when the scope ends
public:
    explicit Timer(std::string label) : label_(std::move(label)) { std::cout << "[start " << label_ << "]\n"; }
    ~Timer() { std::cout << "[end " << label_ << "]\n"; }
private:
    std::string label_;
};

class Connection {                              // pretend network/database connection
public:
    explicit Connection(std::string host) : host_(std::move(host)) { std::cout << "  connect " << host_ << '\n'; }
    ~Connection() { std::cout << "  disconnect " << host_ << '\n'; }
    void query(const std::string& q) {
        if (q.empty()) throw std::runtime_error("empty query");
        std::cout << "  run: " << q << '\n';
    }
private:
    std::string host_;
};

void sync(bool fail) {
    Connection db("db.budgetbuddy.app");
    db.query("SELECT * FROM expenses");
    if (fail) db.query("");                     // throws: db's destructor STILL runs
    std::cout << "  sync finished\n";
}

int main() {
    Timer t("main");
    {
        Timer a("first");
        Timer b("second");
        std::cout << "inside block\n";
    }                                           // destroyed in reverse order: second, first

    std::cout << "Normal sync:\n";
    sync(false);
    std::cout << "Failing sync:\n";
    try {
        sync(true);
    } catch (const std::exception& e) {
        std::cout << "  caught: " << e.what() << '\n';
    }
    return 0;
}

/* Output:
[start main]
[start first]
[start second]
inside block
[end second]
[end first]
Normal sync:
  connect db.budgetbuddy.app
  run: SELECT * FROM expenses
  sync finished
  disconnect db.budgetbuddy.app
Failing sync:
  connect db.budgetbuddy.app
  run: SELECT * FROM expenses
  disconnect db.budgetbuddy.app
  caught: empty query
[end main]
*/