skip to content

In C++, why does a std::lock_guard still unlock its mutex when the function holding it throws an exception?

level: juniorimportance: must knowfreq 80%

answer

  1. cleanup lives in the destructor
  2. the exception leaves the scope
  3. stack unwinding destroys automatic objects
  4. reverse order of construction

basics

~20 s

A std::lock_guard unlocks its mutex in its destructor, and stack unwinding destroys every fully constructed automatic object between the throw and the matching handler, so the unlock runs on the error path as well as on a normal return.

solid answer

~40 s

This is RAII: the resource is acquired in a constructor and released in the matching destructor. `std::lock_guard` calls `lock()` when it is constructed and `unlock()` in `~lock_guard()`; `std::ofstream` opens a file and its buffer's destructor calls `close()`. When an exception propagates toward a handler, the standard's **stack unwinding** destroys each automatic object constructed since the `try` block was entered, in the reverse order of their construction, so the guard's destructor runs on the throwing path exactly as it would at a `return`. No `catch` block has to remember to unlock. The guarantee needs a handler somewhere: if no handler is found, whether the stack is unwound before `std::terminate` is implementation-defined, and `std::exit` does not destroy automatic objects at all.

code

cpp · 27 lines
cpp
#include <fstream>
#include <iostream>
#include <mutex>
#include <stdexcept>

std::mutex schema_mutex;

void apply_step(int step) {
    std::lock_guard<std::mutex> guard(schema_mutex);   // locked here
    std::ofstream log("migration.log", std::ios::app); // opened here
    log << "step " << step << '\n';
    if (step == 2) throw std::runtime_error("bad column type");
    // ... more work ...
}   // log closed, then mutex unlocked: reverse order of construction

int main() {
    for (int step = 1; step <= 3; ++step) {
        try {
            apply_step(step);
        } catch (const std::exception& e) {
            std::cout << "step " << step << " failed: " << e.what() << '\n';
        }
        bool free_again = schema_mutex.try_lock();
        std::cout << "mutex free after step " << step << ": " << free_again << '\n';
        if (free_again) schema_mutex.unlock();
    }
}

go deeper

for a junior

Recall the pairing: the constructor acquires, the destructor releases, and destructors of local objects run when an exception leaves their scope. Say RAII by name.

for a middle

Explain stack unwinding precisely: automatic objects constructed since the try block was entered are destroyed in reverse order before the handler runs, and only fully constructed objects count.

for a senior

Show you know where the guarantee stops: an exception with no handler may not unwind, std::exit skips automatic objects, and a destructor swallows close errors, so confirmable writes close explicitly.

for a principal

Frame RAII as the reason a codebase can ban manual unlock and close calls in review, and say which resources still need an explicit, checked release step.

## RAII in one sentence **RAII** (resource acquisition is initialization) ties a resource to the lifetime of an object: the constructor acquires it and the destructor releases it. Because C++ calls destructors at well-defined points, the release happens without anyone writing it at every exit of a function. The resource can be anything with an acquire/release pair: a mutex, a file, a socket, a database transaction, a temporary directory. The idea pays off on the paths a programmer forgets. A function with three early `return` statements and two calls that can throw has five exits; a manual `unlock()` must appear on every one of them. A `std::lock_guard` declared at the top covers them all. ## What stack unwinding guarantees When a `throw` expression runs, control leaves the current function and travels outward to the nearest matching `catch`. The standard calls the clean-up that happens on the way **stack unwinding** (the subclause on stack unwinding in the exceptions chapter): - every object with **automatic storage duration** that has been constructed, but not yet destroyed, since the `try` block was entered is destroyed; - they are destroyed in the **reverse order of the completion of their construction**; - the destructors run **before** the handler's body is entered, so the handler already sees the mutex unlocked and the file closed; - an object whose constructor never finished is not destroyed, because it never existed; its already-built subobjects are. What unwinding does **not** touch: objects created with `new` and held by a raw pointer (the pointer is destroyed, the object is not), and anything outside the scopes being left. ## lock_guard and fstream as RAII types | Type | Acquired in the constructor | Released in the destructor | |---|---|---| | `std::lock_guard<std::mutex>` | `m.lock()` | `m.unlock()` | | `std::ofstream` / `std::ifstream` | opens the file (when given a name) | its `std::basic_filebuf` calls `close()` | | `std::unique_lock<std::mutex>` | locks, unless a tag such as `std::defer_lock` says otherwise | unlocks if it owns the lock | `std::lock_guard` has deleted copy operations and no `unlock()` member: it is the simplest possible guard, locked for exactly its own scope. The `std::basic_filebuf` destructor calls `close()` and, if an exception occurs during that, catches it and does not rethrow, which is why a destructor is a poor place to learn that a final flush failed. ## A migration step, traced A schema migration tool applies a step under a mutex and appends to a log file: 1. `std::lock_guard<std::mutex> guard(schema_mutex);` locks the mutex. 2. `std::ofstream log("migration.log", std::ios::app);` opens the log. 3. The step throws `std::runtime_error("bad column type")`. 4. Unwinding destroys `log` first (the file is flushed and closed), then `guard` (the mutex is unlocked). 5. The `catch` in the caller runs, and the next step can lock the mutex again. Nothing in the `catch` mentions the mutex or the file. Moving the `throw` to a different line, or adding an early `return`, changes nothing about the clean-up. ## When the destructor does not run The guarantee has edges, and a candidate who knows them sounds like someone who has debugged it: - **No handler at all.** If an exception escapes `main` (or a thread's function) with no matching `catch`, it is implementation-defined whether the stack is unwound before `std::terminate` is called. Code that needs the clean-up catches at the top level. - **`std::exit`.** Objects with automatic storage duration are not destroyed by calling `std::exit`; `std::abort` destroys nothing. - **A heap object behind a raw pointer.** `Guard* g = new Guard(m);` is never released by unwinding; only a scoped owner makes it so. - **An unnamed temporary.** `std::lock_guard<std::mutex>{m};` builds a guard that is destroyed at the end of that statement, so nothing after it is protected. ## Why not catch, unlock and rethrow? Before RAII became the norm, code released resources by hand: ```cpp schema_mutex.lock(); try { apply(step); } catch (...) { schema_mutex.unlock(); throw; } schema_mutex.unlock(); ``` It works for one resource and one exit, and decays from there: - every new resource adds another `try` level, and the release calls must be kept in the right order by hand; - every early `return` added later needs its own `unlock()`, and the compiler will not point out a missing one; - a `catch (...)` that forgets the bare `throw;` silently swallows the error; - the release logic is duplicated at each call site instead of written once in a destructor. A guard object replaces all of that with one declaration, and the order of release follows from the order of declaration. ## What to say in an interview Name the mechanism (destructor plus stack unwinding), the order (reverse of construction), and one edge (an uncaught exception may not unwind). That answers the question a junior is asked and shows the depth a middle engineer is expected to have.

  • Is a std::lock_guard's destructor guaranteed to run if the exception is never caught anywhere?
    No. When no matching handler exists, the standard makes it implementation-defined whether the stack is unwound before `std::terminate` is called, so the destructor may never run. A program that relies on destructor clean-up (flushing a log, releasing a lock file) catches at the top of `main` and of every thread function, then exits deliberately.
  • Why can't a std::ofstream's destructor tell you that the final flush to disk failed?
    Its `std::basic_filebuf` destructor calls `close()` and, if an exception occurs, catches it and does not rethrow; a destructor also returns nothing. When a write must be confirmed, call `close()` yourself before the scope ends and check the stream's state (`fail()`), so the error surfaces where it can still be handled.

  • The mutex stays locked unless a catch block calls unlock() on it
  • Destructors only run when a function returns normally, not on an exception
  • Every uncaught exception is guaranteed to unwind the stack before terminating
  • An object created with new is destroyed when the scope holding its pointer unwinds
  • Reliable cleanup in C++ needs a finally block around the code