Module 8 · Lesson 7 of 90

Destruction order and exceptions

The learner can trace construction and destruction order through a base-and-derived object and explain stack unwinding and the basic exception guarantee.

  • Beginner to advanced
  • 7 min read
  • 6 min lab
What you will need

g++ 13 or newer, CMake 3.20 or newer, and Make or Ninja on Ubuntu 24.04 (WSL2, VM or container); no special hardware for this lesson

Your place in the module
By the end you can 3 objectives
  • Trace the construction and destruction order of base subobjects, members, and the constructor body.
  • Explain why a polymorphic base needs a virtual destructor and what it costs.
  • Describe stack unwinding and the basic exception-safety guarantee.
Video coming soonDestruction order and exceptions
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from CMake project setup
  • Modern CMake describes targets and their usage requirements; PRIVATE, PUBLIC and INTERFACE control what consumers inherit.
  • CMake generates files for a native build tool; you configure with -S and -B, build with cmake --build, and CMAKE_BUILD_TYPE selects the optimization flags.
  • CTest marks a test passed when its process exits with status 0, and --output-on-failure prints the failing test's own output.
01

Construction and destruction order, traced

5 min read

With a build system in place, the code you build must still survive exceptions and predictable teardown. This lesson answers the exact order objects are constructed and destroyed, and how exceptions change that.

The previous lesson established that members initialize in declaration order. Inheritance adds one level above that. When a derived object is constructed, the order is: the base-class parts of the object, called subobjects, first, then the derived class's own members in declaration order, then the derived constructor's body. Destruction is the exact mirror: the derived destructor body, then its members in reverse declaration order, then the base subobjects. The base is the foundation, so it is built first and dismantled last.

Do not take this on faith. Instrument a class and watch. This program prints every construction and destruction:

cpp
#include <iostream>
#include <string>

struct Trace {
    std::string name;
    explicit Trace(std::string n) : name(std::move(n)) {
        std::cout << "  construct " << name << '\n';
    }
    ~Trace() { std::cout << "  destroy " << name << '\n'; }
};

struct Base {
    Trace b{"Base member"};
    Base() { std::cout << "Base body\n"; }
    ~Base() { std::cout << "Base destructor\n"; }
};

struct Derived : Base {
    Trace d1{"Derived first"};
    Trace d2{"Derived second"};
    Derived() { std::cout << "Derived body\n"; }
    ~Derived() { std::cout << "Derived destructor\n"; }
};

int main() {
    std::cout << "enter scope\n";
    Derived obj;
    std::cout << "leave scope\n";
}

Typical output (yours will differ):

text
enter scope
  construct Base member
Base body
  construct Derived first
  construct Derived second
Derived body
leave scope
Derived destructor
  destroy Derived second
  destroy Derived first
Base destructor
  destroy Base member

Read it against the rule: the Base subobject is built first (its member, then its body), then d1 and d2 in declaration order, then the Derived body. At scope exit everything runs backwards. This trace technique is the professional way to settle any lifetime argument, and it is one of the labs.

Step by stepBuilding and dismantling a derived object
  1. Base subobjects: each base class is constructed, in declaration order of the base list.

  2. Members: the derived class's members initialize in declaration order.

  3. Constructor body: the derived constructor's statements run; the object is now live.

  4. Destructor body: at scope exit, the derived destructor's statements run first.

  5. Members in reverse: members are destroyed in reverse declaration order.

  6. Bases in reverse: base subobjects are destroyed last, in reverse order.

Two constructor tools from C++11 reduce duplication in exactly this machinery. A delegating constructor calls another constructor of the same class:

cpp
class Config {
public:
    Config() : Config("default.conf") { }   // delegates to the constructor below
    explicit Config(std::string path) : path_(std::move(path)) { }
private:
    std::string path_;
};

The delegating constructor's initializer list may name only the class itself; the target constructor initializes all the members. An inheriting constructor pulls the base's constructors into the derived class:

cpp
struct Base {
    explicit Base(int pin) : pin_(pin) { }
    int pin_;
};
struct Derived : Base {
    using Base::Base;    // inherit Base(int)
};
Derived d{17};           // calls Base(17)

Members that Derived adds still follow their own initializers; the inherited constructor only forwards to the base.

Now the destruction corner that bites real projects. A class with virtual functions is called polymorphic: code can hold a base pointer while the derived class's behaviour runs. If a class is meant to be used that way and deleted through a base pointer, its destructor must be virtual:

cpp
struct Device {
    virtual ~Device() = default;   // without virtual, the delete below is undefined behaviour
    virtual void sample() = 0;
};
struct I2cSensor : Device {
    ~I2cSensor() override { /* release the bus handle */ }
    void sample() override { /* read the sensor */ }
};
void run(Device* d) {
    d->sample();
    delete d;   // calls ~I2cSensor first, then ~Device
}

Without the virtual on ~Device, delete d destroys only the Device part. The I2cSensor destructor never runs, its resources leak, and the behaviour is undefined, not merely incomplete. The cost of the fix is visible in the object's size:

cpp
struct Plain { int x; };
struct Poly  { int x; virtual ~Poly() = default; };
// std::cout << sizeof(Plain) << ' ' << sizeof(Poly);

On a typical 64-bit Linux build with GCC or Clang this prints 4 16: the polymorphic object gains an 8-byte hidden pointer, plus padding. GCC's -Wnon-virtual-dtor and Clang's -Wdelete-non-virtual-dtor flag the dangerous pattern; keep them on.

Look at those 16 bytes offset by offset:

sizeof(Poly) is 16: bytes 0 to 7 hold the vptr, bytes 8 to 11 hold x, bytes 12 to 15 are padding. Plain, with the same int and no virtual functions, is just those 4 bytes. Enter 0x8 to find the member, or 0xF to land in the padding.

  • regions: [{"name": "vptr", "start": "0x0", "size": "8", "detail": "Hidden pointer to the class vtable, at offset 0 under the Itanium C++ ABI"}, {"name": "x", "start": "0x8", "size": "4", "detail": "The int member - the only data this object stores"}, {"name": "padding", "start": "0xC", "size": "4", "detail": "Trailing padding: 8-byte alignment rounds 12 used bytes up to 16"}]
Going deepervptr and vtable layout

The hidden pointer is the vptr, and it points at the class's vtable, a static array of function pointers shared by every object of the class. Under the Itanium C++ ABI, the binary convention GCC and Clang follow on Linux, the vptr sits at offset 0 of the object, and the vtable holds, before the function pointers, an offset-to-top value and a pointer to the typeinfo used by dynamic_cast and typeid. Each virtual call loads the vptr, indexes the vtable, and calls through the pointer, which is why virtual dispatch costs one extra indirection and defeats some inlining.

A virtual destructor actually occupies two vtable slots: the complete-object destructor and the deleting destructor, which calls the destructor and then operator delete. When you write delete d, the compiler emits a call through the deleting-destructor slot, so the most-derived destructor runs and the correct amount of memory is freed. That is the mechanism behind the rule: no virtual destructor, no dispatch, and the base's fixed size and cleanup are all you get.

Construction and destruction orderBase constructorsMembersdeclarationorderConstructorbodyObject liveDestructorbodyMembersreverseorderBasedestructorsBase constructorsMembersdeclarationorderConstructorbodyObject liveDestructorbodyMembersreverseorderBasedestructors
Construction: bases, members, body. Destruction: the exact reverse.
Instrument constructors and destructors and read the order trace
Recording coming soon. Follow the commands in this lesson.
02

Exceptions, stack unwinding, and the basic guarantee

5 min read

You have seen RAII survive exceptions; now look at the mechanism. When a throw executes, the runtime searches for a handler: it walks back out through the function's scopes and then up the call chain, looking for a try block with a matching catch. The walk itself is . Every fully constructed automatic object in every scope the exception passes through is destroyed, exactly as if the scope had ended normally.

cpp
void process(const std::string& path) {
    FileHandle f(path);              // acquired first
    std::vector<int> samples(1024);  // acquired second
    // ... fill samples ...
    throw std::runtime_error("sensor timeout");
}

int main() {
    try {
        process("samples.bin");      // create the file first, e.g. touch samples.bin
    } catch (const std::runtime_error& e) {
        std::cout << "caught: " << e.what() << '\n';
    }
}

Between the throw and the catch, unwinding destroys samples first (constructed second), freeing its heap buffer, then f, closing the descriptor. The handler runs only after both are gone. No leak is possible, and no cleanup code was written at the throw site.

Step the unwinding by hand, including the two ways it ends in a dead process:

A throw destroys automatic objects newest first: samples frees its heap buffer, then f closes the descriptor, and only after both are gone does the catch block in main run. Press destructor throws, or no handler anywhere, and the runtime calls std::terminate instead: the process dies, which is why destructors are implicitly noexcept and must never throw.

  • states: [{"id": "live", "label": "Live in process()"}, {"id": "unwind_vector", "label": "Destroying samples, the vector"}, {"id": "unwind_handle", "label": "Destroying f, the FileHandle"}, {"id": "caught", "label": "Inside the catch block"}, {"id": "terminating", "label": "std::terminate: the process dies"}]
  • transitions: [{"from": "live", "to": "unwind_vector", "event": "throw"}, {"from": "unwind_vector", "to": "unwind_handle", "event": "continue unwinding"}, {"from": "unwind_handle", "to": "caught", "event": "matching catch found"}, {"from": "unwind_vector", "to": "terminating", "event": "destructor throws"}, {"from": "unwind_handle", "to": "terminating", "event": "destructor throws"}, {"from": "unwind_vector", "to": "terminating", "event": "no handler anywhere"}, {"from": "unwind_handle", "to": "terminating", "event": "no handler anywhere"}]

This is what the means, and RAII gives it to you for free for anything you own. The program state may have changed, but it is consistent: no half-freed buffers, no held locks, no open descriptors. Stronger promises exist, the strong guarantee (the operation either completes or has no effect) and the nothrow guarantee, and M8-S05A covers them; the basic guarantee is the floor every function should meet.

Destructors have a special duty here. Since C++11 a destructor is implicitly noexcept, a specifier promising the function will not throw. If a destructor does throw while unwinding is already in progress, the runtime calls std::terminate and the process dies. The rule is absolute: destructors release resources and swallow or log errors; they never throw. If release can fail in a way the caller must know about, provide an explicit close() or commit() that reports errors while the object is still alive, like the fstream detail from section 4.

One more corner: if no matching handler exists anywhere, std::terminate runs, and the standard does not even guarantee that unwinding happens first. A program that relies on destructors running after an uncaught exception is relying on implementation-defined behaviour. Catch at a defined boundary, such as the top of main or a thread's entry function.

Embedded profiles without exceptions

Many embedded C++ codebases compile with -fno-exceptions to save binary size and avoid unpredictable timing. RAII still works: scope-exit destruction does not need exceptions, so owners still release on every return path. What changes is error handling: throws are replaced by return codes or std::expected, which M8-S05 covers. Write your RAII classes so they work in both worlds: constructors that can fail take an error-code path or a factory function instead of throwing.

Going deeperZero-cost exceptions: tables instead of checks

The Itanium ABI implementation used by GCC and Clang is called zero-cost because the happy path executes no extra instructions: no check after every call, no registration of cleanup handlers at scope entry. Instead, the compiler emits static tables. The .eh_frame section describes how to restore registers and find each frame's return address; the .gcc_except_table section holds a language-specific data area (LSDA) per function, listing which ranges of code are covered by which catch clauses and which cleanups must run. When a throw happens, the unwinder walks the frames using .eh_frame and consults each LSDA, calling a personality routine, __gxx_personality_v0 for C++, to decide whether a frame handles the exception or only needs cleanup. The cost model is therefore: zero time when nothing throws, a slow walk when something does, and extra read-only data in the binary. On a flash-constrained device those tables are a real size cost, which is one reason -fno-exceptions profiles exist.

Stack unwinding to a handlerThrow siteUnwinderLocal objectsHandlerthrowruntime_errorsearch for matching catchdestroy inreverse orderbuffer freed,fd closedcontrol reaches catch1. Throw site → Unwinderthrow runtime_error2. Unwinder → Handlersearch for matching catch3. Unwinder → Local objectsdestroy in reverse order4. Local objects → Unwinderbuffer freed, fd closed5. Unwinder → Handlercontrol reaches catch
A throw unwinds through the scopes, destroying automatic objects in reverse order, then reaches the handler
Throw through a scope with RAII owners and watch both release
Recording coming soon. Follow the commands in this lesson.

Key takeaways

  • Automatic objects are destroyed in reverse construction order when a scope exits, including during exception unwinding.
  • A polymorphic base needs a virtual destructor; deleting through a base pointer without one is undefined behaviour.
  • Construction builds base subobjects, then members, then the body; destruction is the exact reverse.
  • A destructor is implicitly noexcept; if one throws during unwinding the process calls std::terminate.
Reflect
  1. Explain to a colleague, in two sentences: trace the construction and destruction order of base subobjects, members, and the constructor body.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close