skip to content

Resource Ownership

RAII ties a resource to an object's lifetime, and unique_ptr and shared_ptr say who owns heap memory. Junior interviews start here because leaks and double frees start here.

on this pageshow

explore

questions

20

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
open as a page

In C++, why does copying a std::unique_ptr fail to compile, and how do you hand its object to a new owner?

level: juniorimportance: must knowfreq 80%

basics

~20 s

std::unique_ptr deletes its copy constructor and copy assignment, because two copies would both delete the same object. Ownership is moved instead: std::move hands it to the new owner, and the source is left holding nullptr.

open as a page

In C++, why is std::make_unique preferred over writing std::unique_ptr<T>(new T(...)) yourself?

level: juniorimportance: must knowfreq 70%

basics

~20 s

std::make_unique (C++14) names the type once and keeps new out of the code, so no raw owning pointer exists even briefly. Before C++17 it also prevented a leak when another argument of the same call threw.

open as a page

In C++, in what order are a class's members, its base classes and a function's local objects destroyed, and why?

level: middleimportance: must knowfreq 68%

basics

~20 s

Destruction mirrors construction: locals die in reverse order of construction, and a destructor runs its body, then destroys data members in reverse declaration order, then base classes in reverse order, so nothing outlives what it depends on.

open as a page

In C++, what does a std::shared_ptr's control block hold, and what changes when you create the object with std::make_shared?

level: middleimportance: must knowfreq 70%

basics

~20 s

In libc++ and libstdc++ the control block holds the strong count, the weak count and the deleter. std::make_shared builds the object inside that block, one allocation instead of two, but its storage is freed only after the last weak_ptr goes.

open as a page

In C++, what do std::weak_ptr's lock(), expired() and conversion to std::shared_ptr each do, and which belongs in an observer list?

level: middleimportance: must knowfreq 75%

basics

~20 s

lock() returns an owning std::shared_ptr, or an empty one if the object is gone; expired() only reports whether it is gone; std::shared_ptr's constructor from a weak_ptr throws std::bad_weak_ptr instead. Observer lists call lock() and use the result.

open as a page

In C++, when should a function take std::unique_ptr<T> by value, by reference, or a plain T* or T& instead?

level: middleimportance: must knowfreq 70%

basics

~10 s

Take std::unique_ptr<T> by value when the function takes ownership, std::unique_ptr<T>& only when it must reset or replace the caller's pointer, and T& (or T* when null is allowed) when it merely uses the object.

open as a page

In C++, which parts of std::shared_ptr are thread-safe, and what does copying one cost in a multithreaded hot path?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Count updates are safe, so separate shared_ptr copies of one object can live on different threads. Writing one shared_ptr instance while another thread reads it is a data race, the object gets no protection, and each copy costs atomic updates.

open as a page

Why does a C++ std::unique_ptr holding a FILE* from fopen need a custom deleter instead of the default one?

level: juniorimportance: should knowfreq 55%

basics

~20 s

The default deleter, std::default_delete, calls delete, but a FILE* from fopen was not created by new: deleting it is undefined behaviour and never runs fclose, so buffered output is lost. A deleter whose call operator runs fclose fixes it.

open as a page

How do you write a C++ RAII guard for a database transaction that rolls back unless the code reaches commit?

level: middleimportance: should knowfreq 50%

basics

~10 s

Begin the transaction in the constructor, roll back in the destructor unless a commit() call marked it done, delete the copy operations so one guard owns it, and keep the destructor from throwing.

open as a page

In C++, what do std::unique_ptr's release(), reset() and get() each do, and which one leaks when misused?

level: middleimportance: should knowfreq 55%

basics

~20 s

get() returns the pointer and keeps ownership; release() returns it and gives up ownership without deleting; reset(p) deletes the old object and owns p. Ignoring release()'s result leaks, and deleting get()'s result causes a double delete.

open as a page

Why does a custom deleter change a C++ std::unique_ptr's type and possibly its size, but not a std::shared_ptr's?

level: seniorimportance: should knowfreq 45%

basics

~20 s

For std::unique_ptr the deleter is a template argument stored inside the object, so it changes the type and, unless it is an empty type, the size. std::shared_ptr takes the deleter as a constructor argument and hides it in its control block.

open as a page

A C++ function writes std::lock_guard<std::mutex>{counter_mutex}; before incrementing a shared counter, yet the counter still races; why?

level: seniorimportance: should knowfreq 42%

basics

~20 s

The guard has no name, so it is a temporary destroyed at the end of that statement: the mutex is locked and unlocked immediately, and the increment runs unprotected, which is a data race and undefined behaviour.

open as a page

In a C++ async server, why must a session use enable_shared_from_this instead of std::shared_ptr<Session>(this), and when does shared_from_this() throw?

level: seniorimportance: should knowfreq 50%

basics

~20 s

std::shared_ptr<Session>(this) creates a second control block, so two owner groups each delete the session. enable_shared_from_this keeps a weak_ptr set by the first owning shared_ptr; shared_from_this() copies it and, since C++17, throws std::bad_weak_ptr if nothing owns the object.

open as a page

Is std::unique_ptr really free compared with a raw owning pointer in C++, and where does it cost anything at all?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Nearly. With the default deleter it is pointer-sized in libc++ and libstdc++ and dereferences like a raw pointer, but passing it by value goes through memory under the Itanium C++ ABI, and moves and destruction add null stores and checks.

open as a page

As a C++ lead, when would you allow std::shared_ptr in a codebase, and what rules would you set for its use?

level: principalimportance: should knowfreq 40%

basics

~20 s

Default to unique ownership and allow std::shared_ptr only where lifetime is genuinely decided at run time by several parties, such as async callbacks, caches and immutable snapshots, with rules for weak back-edges, const pointees and borrowing instead of copying.

open as a page

As a C++ lead, what ownership convention would you set for a codebase's APIs, including who may hold raw pointers?

level: principalimportance: should knowfreq 35%

basics

~20 s

Make ownership visible in signatures: std::unique_ptr by value to give or take ownership, T& or T* only to borrow, no owning raw pointers outside a few wrappers, and stored non-owning pointers only where the owner provably outlives the holder.

open as a page

In C++23, how do std::out_ptr and std::inout_ptr let a std::unique_ptr receive a handle from a C function's pointer-to-pointer parameter?

level: middleimportance: nice to knowfreq 25%

basics

~10 s

std::out_ptr(p) makes a temporary that stands in for the C function's out-parameter and, at the end of the full-expression, resets p with the handle written into it; std::inout_ptr also passes p's current handle in

open as a page

Why can a C++ std::shared_ptr<std::FILE> with an fclose deleter misbehave after fopen fails, when std::unique_ptr does not?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

std::unique_ptr calls its deleter only for a non-null pointer, but a std::shared_ptr built from a null pointer and a deleter owns that null pointer and calls the deleter with it, so fclose(nullptr) runs, which is undefined behaviour.

open as a page

In C++, what does std::shared_ptr's aliasing constructor do, and when would you hand out a pointer created with it?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

std::shared_ptr<U>(owner, ptr) shares owner's control block but stores ptr, usually a member of the owned object. Holding the member pointer keeps the whole parent alive, so a caller can keep a part safely without knowing about the parent.

open as a page