skip to content

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%

answer

  1. begin in the constructor
  2. a committed flag the destructor checks
  3. copying means two owners
  4. the destructor must not throw

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.

solid answer

~40 s

The guard's constructor calls `db_begin()` and stores the transaction handle; `commit()` commits and then marks the guard as finished; the destructor rolls back only if it was never finished. Any exit that skips `commit()` (an exception, an early `return`) runs the destructor and rolls back. Copying is deleted, because two copies would both roll back the same transaction; a move can transfer it if the moved-from guard is marked empty so its destructor does nothing. The destructor is implicitly `noexcept`, so a rollback that can fail must catch and log its own error rather than throw: an exception escaping it calls `std::terminate`. When the guard must know whether it is being destroyed by an exception, C++17's `std::uncaught_exceptions()` compared with the value saved at construction tells it.

code

cpp · 33 lines
cpp
#include <iostream>
#include <stdexcept>
#include <utility>

int  db_begin()          { std::cout << "BEGIN\n"; return 7; }   // stand-ins for
void db_commit(int id)   { std::cout << "COMMIT " << id << '\n'; }   // a database
void db_rollback(int id) { std::cout << "ROLLBACK " << id << '\n'; } // client API

class Transaction {
public:
    Transaction() : id_(db_begin()) {}
    Transaction(const Transaction&) = delete;             // one owner only
    Transaction& operator=(const Transaction&) = delete;
    Transaction(Transaction&& other) noexcept
        : id_(std::exchange(other.id_, -1)) {}            // source gives it up
    ~Transaction() { if (id_ != -1) db_rollback(id_); }   // never committed
    void commit() { db_commit(id_); id_ = -1; }
private:
    int id_;
};

void migrate(bool fail) {
    Transaction txn;
    if (fail) throw std::runtime_error("ALTER TABLE failed");
    txn.commit();
}

int main() {
    migrate(false);
    try { migrate(true); } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << '\n';
    }
}

go deeper

for a junior

Recall the split: begin in the constructor, roll back in the destructor, and commit by an explicit call when the work succeeded.

for a middle

Explain the committed flag and why copy operations are deleted, and show that a move must leave the source empty so only one destructor acts.

for a senior

Show the failure paths: a commit that throws must leave the guard active, a destructor must not let a rollback exception escape, and uncaught_exceptions detects unwinding.

for a principal

Argue when a named guard type beats a generic scope guard in a shared codebase, and where release errors must be reported instead of swallowed.

## The problem the guard solves A migration step begins a transaction, runs a series of `ALTER TABLE` statements, and commits. Any statement can fail by throwing, and the function may also return early. Without a guard, every exit needs its own rollback call, and the one that is forgotten leaves a transaction open, holding locks in the database, until the connection dies. An **RAII guard** moves the rollback into a destructor, so the language runs it on every exit. Commit stays explicit, because only the code knows when the work succeeded. ## The shape of the guard 1. **Constructor** acquires: it begins the transaction and stores its handle. If beginning fails, the constructor throws and no guard exists, so nothing is rolled back. 2. **`commit()`** performs the commit and then marks the guard as finished (the sketch sets the handle to `-1`). Marking it after the call matters: if the commit itself throws, the guard is still active and the destructor rolls back. 3. **Destructor** releases conditionally: roll back only if the guard is still active. 4. **Copy constructor and copy assignment are deleted**: a copy would be a second owner, and two destructors would each roll back (or one would roll back what the other committed). 5. **Move constructor** (optional) transfers ownership with `std::exchange`, leaving the source marked empty, so a guard can be returned from a factory function. ## Ownership and copying | Operation | What the guard does | Why | |---|---|---| | Copy construct / copy assign | deleted | one transaction, one owner | | Move construct | takes the handle, empties the source | a factory can return a guard | | Destroy while active | rolls back | the code never reached `commit()` | | Destroy after `commit()` or move | does nothing | the handle is already released or handed on | How a move constructor is written in general, and the rules for which special members the compiler declares, belong with move semantics and the class special members; here they matter only as the guard's ownership policy. ## The destructor must not throw A destructor without a `noexcept` specifier gets the exception specification of the implicitly declared one, which for ordinary members is non-throwing. So if `db_rollback` throws out of `~Transaction()`, `std::terminate` is called. That is worse during unwinding: the guard is often being destroyed **because** an exception is already in flight. Practical rules: - make the release path non-throwing, or wrap it in `try { ... } catch (...) { /* log */ }`; - report failures that the caller must handle from a named member (`commit()`), never from the destructor; - keep the destructor short: it runs on paths nobody tests. The guarantees a function gives callers when it fails are a separate topic; the guard is the tool that makes them achievable. ## Knowing why the destructor runs Sometimes a guard should act differently on success and on failure without an explicit `commit()`. C++17 added `std::uncaught_exceptions()`, which returns the number of exceptions currently in flight in the thread: - save the count in the constructor; - in the destructor, a larger count means this scope is being left by an exception, so roll back; - an equal count means a normal exit. The older `std::uncaught_exception()` (singular) returned a single `bool` that was `true` for every destructor running during unwinding, even for a guard created and left normally inside another object's destructor; C++17 deprecated it and C++20 removed it. ## Mistakes that break the guard - **Committing in the destructor.** It hides the success decision inside clean-up code and commits half-finished work when an exception unwinds the scope. - **Forgetting to mark the moved-from guard empty.** Both the source and the target then roll back the same handle. - **Declaring the guard after the statements it should protect.** Only what follows its declaration is covered; work before it runs outside the transaction. - **Holding the guard in a longer-lived object by accident.** A guard stored as a member of a long-lived service keeps the transaction open for that object's whole lifetime. ## Generic scope guards The same pattern generalises to "run this lambda when the scope ends unless dismissed": a small class template holding a callable and an `active` flag. It is useful for one-off clean-up (delete a temporary file, restore a setting), but a named type like `Transaction` documents intent better when the resource recurs.

  • Why does the guard clear its handle after the commit call rather than before it?
    If the commit itself throws, the transaction is still open and must be rolled back. Clearing the handle only after `db_commit` returns keeps the guard active on that failure, so the destructor, run by unwinding, rolls back. Clearing it first would leave an open transaction that nothing releases.
  • How can a guard's destructor tell whether its scope is being left by an exception?
    Save `std::uncaught_exceptions()` (C++17) in the constructor and compare it in the destructor: a larger value means an exception is propagating through this scope. The removed `std::uncaught_exception()` returned only a bool and misreported a guard destroyed inside another object's destructor during unwinding.

  • Make the guard copyable so it can be passed around freely
  • The destructor should throw when rollback fails so callers notice
  • Commit should happen in the destructor so callers never forget it
  • std::uncaught_exception() is the right way to detect unwinding today
  • A failed begin in the constructor still needs a rollback in the destructor