Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 171 ยท Object-Oriented Programming

Destructors and RAII

Learn C++ destructors and RAII - when objects are destroyed, destruction order, wrapping files and locks in classes, cleanup during exceptions, and why RAII beats finally.

A constructor turns memory into a valid object; a destructor does the reverse. It runs automatically at the exact moment an object's lifetime ends and gives the object a last chance to release whatever it holds: memory, an open file, a lock, a network connection. You never call it yourself, and you can't forget it.

That guarantee is the foundation of the most important idiom in C++: RAII, short for Resource Acquisition Is Initialization. The name is awkward, but the idea is simple: tie every resource to an object, acquire it in the constructor, release it in the destructor. Then the resource is released exactly when the object goes away, on every path out of the code, including early returns and exceptions. std::vector, std::string, std::unique_ptr, std::fstream and std::lock_guard are all RAII classes, and in this lesson you'll learn to write your own. It builds on Constructors and Member Initializer Lists and Scope, Lifetime and Storage Duration.

Writing a destructor

A destructor is named after the class with a tilde in front: ~ClassName(). It takes no parameters, returns nothing, and a class has exactly one. If you don't write one, the compiler generates a destructor that simply destroys each member.

C++ When constructors and destructors run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Read the output alongside the code and you'll see the rules:

  • A local object is destroyed when execution leaves its block, whichever way it leaves.
  • Objects in the same scope are destroyed in reverse order of construction: c before a. Later objects may depend on earlier ones, so they must go first.
  • A temporary is destroyed at the end of the full expression that created it (the semicolon).
  • A heap object is destroyed when its owner says so: here when the unique_ptr is reset (or itself destroyed). With raw new, only when you call delete.
  • Static and global objects are destroyed after main returns, in reverse order of their construction.

Members and destruction order

When an object is destroyed, its destructor body runs first, while all members are still alive and usable. Then the members are destroyed, in reverse declaration order. (Base classes come last of all; see Inheritance.) This is the mirror image of construction, so a member can safely use members declared before it in both its constructor and destructor.

C++ Destructor body first, then members in reverse order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

RAII: tie resources to objects

A resource is anything you must give back after using it: heap memory, file handles, sockets, mutex locks, database transactions, GPU buffers. Without RAII, each acquisition needs a matching release on every code path:

C++
// Fragile: every early return and every exception must remember to close.
bool save_report(const char* path, const Report& report) {
    std::FILE* file = std::fopen(path, "w");
    if (!file) return false;
    if (!write_header(file, report)) {
        std::fclose(file);                   // remembered here...
        return false;
    }
    write_rows(file, report);                // ...but if this throws, the file leaks
    std::fclose(file);
    return true;
}

With RAII, a small class owns the handle, and its destructor closes it. The function body no longer contains any cleanup code, and the file is closed on every path.

C++ An RAII wrapper for a C file handle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

When save("big.txt", 10) throws halfway through, the output still shows [closed] before save failed. The exception unwinds the stack, and every fully constructed local object on the way is destroyed. That's the guarantee RAII depends on.

Notice the two = delete lines. If File could be copied, two objects would hold the same handle and both destructors would call fclose on it, a double close. Deleting the copy operations makes the compiler reject that mistake. A resource-owning class must always decide what copying means; Copy Constructors and Copy Assignment and Move Semantics show how to make such a class copyable or movable.

In real code you wouldn't write this class, because the standard library already has RAII file types: std::ifstream and std::ofstream close themselves (Reading and Writing Text Files). And for any C handle, std::unique_ptr with a custom deleter gives you RAII in two lines: auto closer = [](std::FILE* f) { std::fclose(f); }; and std::unique_ptr<std::FILE, decltype(closer)> file{std::fopen(path, "r"), closer}; (see Smart Pointers: std::unique_ptr). Writing it by hand once shows you what those types do.

RAII for locks and other "undo" actions

Resources aren't only things you allocate. A locked mutex must be unlocked; a changed setting must be restored; a started transaction must be committed or rolled back. RAII handles all of them the same way. std::lock_guard locks a mutex in its constructor and unlocks it in its destructor, so a lock can never be left held by an early return or an exception (Mutexes and Locks).

You can also write a general scope guard that runs any lambda when it goes out of scope. It's handy for one-off cleanup that doesn't deserve its own class.

C++ lock_guard and a scope guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The total is always exactly 40000 because each increment happens while the mutex is held, and lock_guard makes it impossible to forget the unlock. A proposed std::scope_exit for this pattern exists in the Library Fundamentals technical specification, but it isn't part of standard C++23, so projects write small guards like this one (or use a library).

Why RAII beats finally

Languages with garbage collection clean up memory automatically, but they can't know when you're done with a file or a lock, so they give you finally blocks or special syntax. In Java:

Java
Lock lock = mutex;
lock.lock();
try {
    FileWriter out = new FileWriter("log.txt");
    try {
        out.write("entry");
    } finally {
        out.close();          // the caller of every resource writes cleanup again
    }
} finally {
    lock.unlock();
}

Java's try-with-resources, C#'s using and Python's with improve on this, but the pattern remains: every user of the resource must remember to use the special syntax. RAII puts the cleanup in one place, the class's destructor, written once by its author:

C++
std::lock_guard lock{mutex};
std::ofstream out{"log.txt"};
out << "entry";
// nothing else: both are released at the closing brace, in reverse order

RAII has several more advantages:

  • Deterministic. Cleanup happens at a precise point (the end of scope), not "sometime later" when a garbage collector runs, so files are flushed and locks released immediately.
  • Composable. A class whose members are RAII types needs no destructor at all: destroying it destroys the members, which release their resources. A std::vector<std::ofstream> closes every file. This is the rule of zero.
  • Exception-safe by construction. Stack unwinding runs destructors, so cleanup can't be skipped by an exception (Exception Safety and noexcept).
  • Works for every resource, not just memory.
C++ Stack unwinding: manual cleanup leaks, RAII doesn't

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Rules for writing destructors

  • Never let an exception escape a destructor. Destructors are implicitly noexcept, so an exception leaving one calls std::terminate and ends the program. If cleanup can fail (closing a file can report a write error), offer an explicit close() member that callers can check, and have the destructor ignore or log the error.
  • Don't call a destructor yourself (obj.~T()) except in low-level code that manages raw storage. Destroying an object twice is undefined behavior.
  • Make base class destructors virtual when objects will be deleted through a base pointer (Virtual Functions and Polymorphism).
  • One class, one resource. A class that owns two raw resources is hard to make exception-safe in its constructor: if acquiring the second throws, the destructor never runs, because the object never finished constructing. Wrap each resource in its own RAII member and the problem disappears, since fully constructed members are destroyed.
  • Prefer not to write one. If all your members are RAII types (strings, vectors, smart pointers, streams), the compiler-generated destructor is already correct.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside one block you create Tracer a{"a"}; and then Tracer b{"b"};. In which order are they destroyed when the block ends?

    Objects in the same scope are destroyed in reverse order of construction, so later objects, which may depend on earlier ones, go first.
  2. 2. A function creates a local std::ofstream, writes to it and then a call throws an exception. What happens to the file?

    When an exception propagates, every fully constructed local object in the scopes being left is destroyed. The stream's destructor closes the file.
  3. 3. Why does the File class in this lesson delete its copy constructor and copy assignment?

    A copied File would share the handle, and both destructors would close it, which is undefined behavior. Deleting the copy operations turns that mistake into a compile error.
  4. 4. What happens if an exception escapes from a destructor?

    Destructors are implicitly noexcept, so a thrown exception that leaves one terminates the program. Handle or log errors inside the destructor instead.
  5. 5. class Report { std::string title_; std::vector<std::string> lines_; std::unique_ptr<Chart> chart_; }; Does Report need a user-written destructor?

    All three members are RAII types, so the compiler-generated destructor already releases everything. This is the rule of zero.

Summary

  • A destructor ~ClassName() runs automatically when an object's lifetime ends: at the end of its scope, at the end of the full expression for temporaries, when its owner deletes it, or after main for statics.
  • Objects are destroyed in reverse order of construction. In a class, the destructor body runs first, then members are destroyed in reverse declaration order.
  • RAII ties a resource to an object: acquire in the constructor, release in the destructor. Cleanup then happens on every path, including early returns and exceptions.
  • RAII classes that own a unique resource must control copying, at least by deleting the copy operations.
  • Standard RAII types (std::vector, std::string, smart pointers, file streams, std::lock_guard) cover most needs; a scope guard handles one-off cleanup.
  • RAII beats finally because the cleanup is written once, runs deterministically and composes automatically.
  • Never throw from a destructor, give each resource its own owner, and prefer classes that need no destructor at all.

Next: Access Specifiers and Encapsulation, where you'll decide what the outside world may see and change.