Exception safety and failure atomicity
What you will learn on this page
Section titled “What you will learn on this page”- What the basic, strong, and nothrow guarantees promise, and how to tell from the requirements which one an operation needs.
- How to find every step that can throw in an operation, including the ones that are easy to miss, such as memory allocation.
- Copy-and-swap: the simplest way to the strong guarantee, and what it costs.
- The prepare, record, commit order, which gives the strong guarantee without copying everything, and why at most one step may both fail and be impossible to undo.
- What
noexceptpromises, and where it is correct to write it. - How to test failure paths by making each allocation fail in turn.
The problem: a transfer that fails halfway
Section titled “The problem: a transfer that fails halfway”A small stock system moves items between warehouses. Its requirements:
- T1 A transfer moves several lines (an item and a quantity) from one warehouse to another.
- T2 A transfer is all or nothing. If any line cannot be moved, no line is moved.
- T3 Every transfer is recorded in an audit store. The store can be unavailable. A transfer that was not recorded must not have happened.
- T4 No count is ever negative.
- T5 Stock is never created or lost by a transfer: the total of both warehouses is the same afterwards.
T4 and T5 are invariants: they must hold after every call, whether it succeeded or not. T2 and T3 are stronger: they say what a failed call must leave behind. The obvious loop meets none of the failure requirements:
- If North has too few of an item, its count goes negative (T4).
- If
to.stock_[line.sku]has to add a new entry to the map and the allocation fails, the quantity has already been taken from North and never arrives anywhere: stock is lost (T5). - If the second line fails, the first has moved (T2).
- If the audit store is down, everything has moved, but nothing was recorded (T3).
The first two break invariants, so the warehouses are left invalid. The last two leave them valid, but in a state the caller did not ask for. Those are two different failures, and C++ has a name for each level of promise.
The three guarantees
Section titled “The three guarantees”An operation that can fail by throwing gives one of these promises about what it leaves behind:
| Guarantee | If it throws | Meets |
|---|---|---|
| none | objects may be invalid or leaked; nothing can be relied on | nothing |
| basic | no leaks, every invariant holds, but the state may have changed | T4, T5 |
| strong | the state is exactly as before the call: all or nothing | T2, T3, T4, T5 |
| nothrow | it never throws; it always succeeds | everything, if possible |
Some points that are easy to get wrong:
- Basic is the minimum for any function. A function without it is a bug, because after a failure nobody can use the object safely, not even to destroy it.
- Strong is about state you can observe, not about every bit of
memory. If your operation calls
reserveon a vector and then fails, the extra capacity is usually acceptable, because no caller can see a difference in behavior. - Strong is a property of one call, not a lock. It says nothing about another thread seeing the objects halfway; that is a concurrency question, for the planned pages on thread safety and synchronization.
- Nothrow is only possible for operations that cannot fail: destructors, swaps, moves of most types, and the final step of a commit. An operation that needs memory or another system can fail, and the honest promise for it is basic or strong.
T2 and T3 ask for the strong guarantee. The rest of the page builds it two ways, after first building the basic one.
Step 1: find every step that can throw
Section titled “Step 1: find every step that can throw”Before choosing an order, list each kind of step the transfer does and whether it can fail. The standard says which library operations throw; the rest follows from the types involved.
| Step | Can it throw? | Can it be undone? |
|---|---|---|
| check a quantity or a count | yes, by design: that is how a check reports a problem | nothing to undo |
look up an item in a std::map (find) |
only if comparing keys throws; comparing std::string keys does not |
nothing to undo |
add an entry to a std::map ([], emplace) |
yes, std::bad_alloc |
yes, by erasing it |
build a std::string, such as the record |
yes, std::bad_alloc |
nothing to undo |
audit.record |
yes, anything; the store may be down | no: it was written |
add or subtract two int counts |
no, but the result can overflow, which is undefined behavior | yes, by subtracting |
move nodes with std::map::merge |
only if comparing keys throws; it allocates nothing | yes, but never needed |
swap two maps or two strings |
no (noexcept) |
yes, by swapping back |
| copy a whole warehouse | yes, std::bad_alloc |
nothing to undo: the original is untouched |
The table shows the shape of the answer. Checks, allocation, and the
audit can fail; find, merge, swap, and arithmetic cannot, once
the counts have been checked so they cannot overflow. A strong
operation does everything in the first group before it changes
anything the caller can see, and only things in the second group
after.
The basic guarantee: line by line
Section titled “The basic guarantee: line by line”Here is the example’s version that gets the invariants right, and no more:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Moves the lines one at a time, then records the transfer.// Basic guarantee. Each line is all or nothing: the checks come first,// the one allocation either works or changes nothing, the overflow check// after it can throw only before any count changes, and the subtraction// cannot throw. But the loop is not all or nothing: if line two fails,// line one has already moved and stays moved, and if the audit fails,// everything has moved with no record. Both warehouses are always valid// (no negative count) and their combined total is kept; that is all.void Warehouse::send_line_by_line(Warehouse& to, const std::vector<Line>& lines, AuditSink& audit) { // &to is the address of the other warehouse and `this` the address of // this one: equal means the caller passed the same warehouse twice. if (&to == this) throw std::invalid_argument("cannot send to the same warehouse"); for (const Line& line : lines) { check_line(line); if (count(line.sku) < line.quantity) throw std::invalid_argument("not enough " + line.sku); // operator[] gives a reference to `to`'s count for this item, // first adding an entry of 0 if there is none. Adding allocates; // if that throws, the map is unchanged. int& there = to.stock_[line.sku]; // may throw; nothing changed yet // If add_checked throws, the assignment never happens and `there` // keeps its old value. (A new entry of 0 cannot overflow, so a // failure here never leaves an extra 0 entry behind.) there = add_checked(there, line.quantity); // Cannot throw. The item is present in this warehouse, because a // missing item counts 0 and the check above needed at least // line.quantity, which is positive; so find never returns end(). stock_.find(line.sku)->second -= line.quantity; } // describe may throw std::bad_alloc, and record may throw: either way // every line has already moved. audit.record(describe(*this, to, lines)); // too late to undo the moves}- Each line is checked before it changes anything, so no count goes negative (T4).
to.stock_[line.sku], which may add an entry and so allocate, comes before North is changed. If it throws, nothing was inserted and this line has not moved. No stock is lost (T5).- But a failure on line two leaves line one moved (T2), and the audit comes after every change (T3). Each line is atomic; the transfer is not.
This is the basic guarantee: after any failure both warehouses are valid, and the total is kept, but the caller cannot tell what moved without looking.
Text description of the diagram
Before the transfer, North has 10 bolts and 4 nuts and South has 1 bolt and no nuts. The transfer asks for 3 bolts, then 5 nuts. After send_line_by_line throws “not enough nut”, North has 7 bolts and 4 nuts, South has 4 bolts and no nuts, and nothing was recorded: the total is the same, but the bolts moved without a record, which is the basic guarantee. After send throws the same error, North and South are exactly as before and nothing was recorded, which is the strong guarantee.
Diagram source (Mermaid)
flowchart LR
subgraph Before["Before the transfer"]
BN["North<br/>bolt 10, nut 4"]
BS["South<br/>bolt 1, nut 0"]
end
subgraph Basic["After the failure: line by line (basic)"]
LN["North<br/>bolt 7, nut 4"]
LS["South<br/>bolt 4, nut 0"]
LA["audit: nothing recorded"]
end
subgraph Strong["After the failure: send (strong)"]
SN["North<br/>bolt 10, nut 4"]
SS["South<br/>bolt 1, nut 0"]
SA["audit: nothing recorded"]
end
Before -->|"send_line_by_line throws: not enough nut"| Basic
Before -->|"send throws: not enough nut"| StrongThe strong guarantee by copy-and-swap
Section titled “The strong guarantee by copy-and-swap”The shortest way to strong is to do the basic version on copies, then swap the copies in:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Strong guarantee, by copy-and-swap: run the basic version on copies of// both warehouses, then swap the finished copies in.// - Everything that can throw (the two copies, every line, describe, and// the audit) happens before the real warehouses change.// - The audit is the last thing send_line_by_line does, so once it has// written a record, nothing after it can throw.// - The two swaps cannot throw.// If anything throws, the copies are destroyed on the way out and the// real warehouses were never touched. The price: both warehouses are// copied in full, however small the transfer.void Warehouse::send_by_copy(Warehouse& to, const std::vector<Line>& lines, AuditSink& audit) { if (&to == this) throw std::invalid_argument("cannot send to the same warehouse"); Warehouse from_copy = *this; // may throw: nothing changed Warehouse to_copy = to; // may throw too: from_copy is destroyed, nothing changed from_copy.send_line_by_line(to_copy, lines, audit); // may throw: only copies changed // Now the transfer is complete, and recorded, on the copies. Swapping // puts the new contents in *this and `to`, and leaves the old // contents in the copies, which are destroyed when the function ends. swap(*this, from_copy); // cannot throw swap(to, to_copy);}- Copying may throw, but then nothing has changed.
- The basic version may throw part way through, but then only the copies have changed, and they are destroyed on the way out.
- If the audit succeeded, the transfer is complete on the copies, and
two
swapcalls that cannot throw put them in place.
Copy-and-swap turns an operation with the basic guarantee into one
with the strong guarantee, if its only effects are on the copied
objects, plus at most one step that cannot be undone, which must come
last. send_by_copy is strong only because send_line_by_line
records the audit as its last step that can throw; if it recorded
first, a failure would leave a record of a transfer that never
happened, and no swap would remove it. The ordering rule below is the
general form of this. Copy-and-swap also needs a noexcept swap,
which the class provides:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One warehouse: a name, and how many of each item (sku) it holds. It can// receive stock and send stock to another warehouse, recording each// transfer in an audit store. The three send functions do the same job// with different exception guarantees, so the page can compare them.// Invariant: every count is at least zero.class Warehouse {public: // Takes the name by value and moves it into the member: one copy at // most, made by the caller. `explicit`: a plain string does not turn // into a Warehouse by accident. explicit Warehouse(std::string name) : name_(std::move(name)) {}
// Copy-and-swap: copy first (may throw, changes nothing), then swap, // which cannot throw. One function serves copy and move assignment. // The move constructor is noexcept exactly when moving a std::string // and a std::map is; the tests check that with static_assert. // `= default`: the compiler writes these, copying (or moving) name_ // and then stock_. Copying allocates, so it may throw std::bad_alloc. Warehouse(const Warehouse&) = default; Warehouse(Warehouse&&) = default; // `other` is a parameter taken by value, so the caller builds it // before this body runs: `a = b` copies b into it, and // `a = std::move(b)` moves b into it. If that copy throws, it throws // in the caller, before this function starts, and *this is untouched. // The body only swaps, which cannot throw, so the noexcept is true. // When the function returns, `other`, now holding the old contents, // is destroyed. Result: strong copy assignment, nothrow move. Warehouse& operator=(Warehouse other) noexcept { swap(*this, other); return *this; } // Exchanges the contents of two warehouses. Each member's swap only // trades the internal pointers and sizes: nothing is copied or // allocated, so it cannot throw (nothrow guarantee). A friend defined // inside the class is an ordinary function, not a member; a call // such as swap(a, b) finds it because its arguments are Warehouses. friend void swap(Warehouse& a, Warehouse& b) noexcept { a.name_.swap(b.name_); a.stock_.swap(b.stock_); }
const std::string& name() const noexcept { return name_; } // How many of `sku` it holds; 0 for an item it has never had. int count(const Sku& sku) const noexcept; // All counts added up, in a long long so the sum of many ints fits. long long total() const noexcept; // Adds `quantity` of `sku`. Throws std::invalid_argument unless the // quantity is positive, std::overflow_error if the count would not // fit in an int, std::bad_alloc if memory runs out. void receive(const Sku& sku, int quantity); // strong guarantee
// Each sends every line to `to` and records it, or throws. // All three throw std::invalid_argument when `to` is this warehouse, // a quantity is not positive, or there is not enough of an item; // std::overflow_error when a count would not fit in an int; // std::bad_alloc when memory runs out; and whatever audit.record // throws. They differ in what is left behind when they throw. void send_line_by_line(Warehouse& to, const std::vector<Line>& lines, AuditSink& audit); // basic guarantee void send_by_copy(Warehouse& to, const std::vector<Line>& lines, AuditSink& audit); // strong guarantee void send(Warehouse& to, const std::vector<Line>& lines, AuditSink& audit); // strong guarantee
// Equal when the names match and both maps hold the same items with // the same counts (an entry kept at 0 still counts); the tests use it to // compare a warehouse with a copy taken before a failed transfer. friend bool operator==(const Warehouse&, const Warehouse&) = default;
private: // The last step of send: applies a transfer that has already been // checked and prepared, using only steps that cannot throw. void commit(Warehouse& to, const std::map<Sku, int>& wanted, std::map<Sku, int>& new_items) noexcept;
std::string name_; std::map<Sku, int> stock_; // sku to count, kept sorted by sku};The same idea gives the class a strong copy assignment.
operator= takes its argument by value, so the copy is made by
the caller before the function body runs; the body only swaps. A
defaulted copy assignment (= default) would assign name_ and then
stock_, and if copying stock_ threw, the warehouse would have the
new name and a stock that may be only partly copied: only basic.
The cost is the copy: both warehouses, every item, each time, however small the transfer. For two small maps that is nothing. For a warehouse with a million items, or for objects that hold resources that cannot be copied, it is the wrong tool.
The strong guarantee by prepare, record, commit
Section titled “The strong guarantee by prepare, record, commit”send gets the same guarantee without copying anything except what it
adds:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Strong guarantee, by prepare, record, commit, without copying the// warehouses. Steps 1 and 2 may throw but change only local objects;// step 3 is the one step that cannot be undone, and it either works or// throws having written nothing; step 4 cannot throw. So when send// throws, both warehouses are exactly as they were and nothing was// recorded. This relies on the AuditSink rules: record is all or// nothing, and does not change any Warehouse.void Warehouse::send(Warehouse& to, const std::vector<Line>& lines, AuditSink& audit) { if (&to == this) throw std::invalid_argument("cannot send to the same warehouse");
// 1. Check everything, changing nothing. Lines for the same item add up. std::map<Sku, int> wanted; // item to the total asked for, over all lines for (const Line& line : lines) { check_line(line); // A reference to this item's running total, which starts at 0 the // first time the item is seen. int& sum = wanted[line.sku]; sum = add_checked(sum, line.quantity); } // `const auto& [sku, quantity]` names the two halves of each map // element (a structured binding). for (const auto& [sku, quantity] : wanted) { if (count(sku) < quantity) throw std::invalid_argument("not enough " + sku); // Only the check matters; the sum itself is thrown away. After // this loop, every subtraction and addition in commit is known to // be safe. add_checked(to.count(sku), quantity); // throws if it would not fit }
// 2. Do every step that may throw on objects nobody else can see. // The only allocations `to` will need are entries for items it does // not have yet. Make them now, each with a count of 0, in a map of our // own: if one fails, this local map is destroyed and `to` never knew. std::map<Sku, int> new_items; // a node for each item `to` lacks for (const auto& [sku, quantity] : wanted) { if (!to.stock_.contains(sku)) new_items.emplace(sku, 0); } // The record's text is built now too, because building it allocates. const std::string entry = describe(*this, to, lines);
// 3. The one step that cannot be undone. If it throws, nothing changed. audit.record(entry);
// 4. Change the real objects using only steps that cannot throw. commit(to, wanted, new_items);}
// Nothrow guarantee, and it must be: it runs after the record is written,// when a failure could no longer be undone. If something in here did// throw, noexcept would stop the program with std::terminate rather than// leave half a transfer.void Warehouse::commit(Warehouse& to, const std::map<Sku, int>& wanted, std::map<Sku, int>& new_items) noexcept { // merge relinks each node of new_items into to.stock_ (none of those // items is in `to`, by step 2), leaving new_items empty. No copying, // no allocation; it could only throw if comparing two keys threw, // and comparing std::string keys does not. That is why new_items is // passed as a non-const reference: its nodes are taken out of it. to.stock_.merge(new_items); // moves the prepared nodes; allocates nothing for (const auto& [sku, quantity] : wanted) { stock_.find(sku)->second -= quantity; // present: checked in step 1 to.stock_.find(sku)->second += quantity; // present: merged above }}The four steps follow the table from Step 1:
- Check everything first, changing nothing. Lines for the same item are added up before checking, so two lines of 3 nuts each are checked as 6. The overflow check means the commit’s additions are always safe.
- Prepare every allocation on objects nobody else can see: a separate map with one node, of count zero, for each item the destination does not have yet, and the text of the record. If anything here throws, these locals are destroyed and the warehouses were never touched.
- Record, the one step that cannot be undone. If the audit store is down, nothing has changed, so throwing is correct (T3).
- Commit with steps that cannot throw.
mergemoves the prepared nodes into the destination’s map without allocating, and the counts change with plain arithmetic on entries that are known to exist.
Two assumptions hold this together, and the AuditSink comment
states them:
recordis itself all or nothing. It writes the whole entry or throws having written nothing. A remote store that can time out after accepting a write breaks this:sendwould leave the stock unchanged while a record exists. The usual fix is to give each transfer an id, so the record can be retried safely and checked afterwards; see Idempotency, retries, and duplicate handling.recorddoes not change the warehouses. It runs code the warehouse does not control, between the checks and the commit. If it changed either warehouse, the checks from step 1 would be stale, andcommitcould subtract from an entry that is gone, which is undefined behavior.
commit is noexcept, and that is a claim with consequences: if any
step inside it threw, the program would stop with std::terminate
instead of leaving half a transfer. It is true here because every
operation in it can only throw if comparing two std::string keys
throws, which it does not.
How this code works: send, traced with real values
The demo’s last transfer, “send, nothing fails”, starts with North at
10 bolts and 4 nuts and South at 1 bolt and no nut entry at all. It
asks for {"bolt", 3}, {"nut", 4}.
| Step | What happens | North | South |
|---|---|---|---|
| 1 | wanted becomes bolt 3, nut 4. North has 10 bolts (at least 3) and 4 nuts (at least 4). South’s counts plus these, 1 + 3 and 0 + 4, fit in an int. |
bolt 10, nut 4 | bolt 1 |
| 2 | South has a bolt entry but no nut entry, so new_items gets one node: nut 0. entry becomes "North -> South: 3 bolt 4 nut". |
bolt 10, nut 4 | bolt 1 |
| 3 | audit.record(entry) writes the record. |
bolt 10, nut 4 | bolt 1 |
| 4a | merge moves the nut 0 node into South’s map; new_items is now empty. |
bolt 10, nut 4 | bolt 1, nut 0 |
| 4b | The loop subtracts and adds: bolt 10 to 7 and 1 to 4, then nut 4 to 0 and 0 to 4. | bolt 7, nut 0 | bolt 4, nut 4 |
The last row is the output’s last two lines. North keeps a nut entry
with a count of 0: commit only changes counts, it does not erase
entries.
If it fails instead. Wherever steps 1 to 3 throw, the only objects
that changed are the locals wanted, new_items, and entry. The
exception leaves send, those locals are destroyed, and both columns
stay as in the first row: that is the strong guarantee. In the demo’s
“not enough nuts” run, step 1 throws at nut 5 (North has 4), before
the bolts are touched. In the “audit fails” run, step 3 throws, and the
prepared nut node is simply freed with new_items.
The ordering rule
Section titled “The ordering rule”The general rule behind both strong versions:
Do everything that can fail before the first change that cannot be undone. After it, do only things that cannot fail.
It explains why the audit is step 3, not step 4. Recording last, after the commit, would mean an unavailable store left the stock moved and unrecorded: the line-by-line result. Recording first, before the checks, would mean a failed check left a record of a transfer that never happened.
It also explains why an operation can have at most one step that
both can fail and cannot be undone. Steps that cannot be undone but
also cannot fail, such as commit itself, may follow freely. With two
that can fail, say an audit record and a message to a
shipping system, one of them must come second, and if it fails the
first has already happened. No ordering fixes that. The usual designs
are:
- Make one of them undoable, for example by recording a “cancelled” entry if the second fails. That is a compensating action, and the state is only eventually consistent. The compensation can fail too, so it must be stored and retried until it succeeds, not tried once.
- Make one of them local and transactional and send the other later from it. That is the outbox on Transaction and persistence boundaries.
Undoing instead of preparing
Section titled “Undoing instead of preparing”A third way to the strong guarantee is to make a change, and undo it
if a later step throws. Ownership graphs and lifetime
design does this when adding a
paragraph: it adds an index entry, then, if the next step throws,
erases it in a catch block and rethrows.
This works when each undo cannot fail itself, such as an erase
or a pop_back. With several steps the catch blocks nest and are
easy to get wrong; a scope guard runs the undo from a destructor
unless the operation is marked complete.
Preparing is usually clearer than undoing when the changes can be built on the side, as here. Undoing is clearer when the change must be made in place to find out whether the next step works.
Where noexcept belongs
Section titled “Where noexcept belongs”noexcept is a promise that no exception leaves the function. If one
tries, the program ends. So the promise must hold for every input,
including when memory runs out. In the example:
| Function | noexcept? |
Why |
|---|---|---|
swap |
yes | it exchanges the pointers inside the members; nothing allocates |
| move constructor | yes, here | it is defaulted, so it is noexcept exactly when moving a std::string and a std::map is; see below |
operator=(Warehouse) |
yes | the copy is made before the call; the body only swaps |
commit |
yes | merge, find, and arithmetic on checked values; the strong guarantee depends on it |
count, total, name |
yes | they read and cannot fail |
| copy constructor | no | it allocates |
receive, send |
no | they allocate, check, and call the audit store |
The move constructor is the subtle one. It takes over the members’
pointers, but the standard does not require std::map’s move
constructor to be noexcept: libstdc++ and libc++ make it so, and
some other standard libraries allocate in it. So the class does not
write noexcept on it; it leaves it defaulted, and the tests check
at compile time that, with the library in use, it is noexcept:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// static_assert checks a condition while the program is compiled: if it// is false, the build fails. Each type trait below asks whether an// operation on Warehouse is declared so that it cannot throw, with the// standard library this build uses. The last one, with `!`, checks the// opposite: copying is not noexcept.// Moving a Warehouse into a new one: noexcept, because the defaulted move// constructor moves a std::string and a std::map, and both are noexcept// here. This is what lets a growing std::vector<Warehouse> move instead// of copy.static_assert(std::is_nothrow_move_constructible_v<Warehouse>);// a = std::move(b): moves b into operator='s parameter, then swaps.static_assert(std::is_nothrow_move_assignable_v<Warehouse>);static_assert(std::is_nothrow_swappable_v<Warehouse>); // the friend swapstatic_assert(!std::is_nothrow_copy_constructible_v<Warehouse>); // copying allocatesThese matter outside this class too. A std::vector<Warehouse> that
grows moves its elements only if the move constructor is noexcept;
otherwise it copies them, to keep its own strong guarantee, as Copy
and move semantics showed.
Two mistakes are common. Writing noexcept on a function that can
allocate turns an out-of-memory error, which a caller might handle,
into an immediate end of the program. And leaving it off a move
constructor or swap that cannot throw makes containers copy instead
of move, and stops other code from building strong operations on top.
Running it
Section titled “Running it”main makes the same failures happen to each version and prints what
is left:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each try_transfer call gets fresh warehouses (North: 10 bolts, 4 nuts;// South: 1 bolt), runs one send function, catches and prints any// exception, and prints both warehouses. &inv::Warehouse::send_line_by_line// is a pointer to that member function, so the same helper can run each// version. The last argument says whether the audit store fails.int main() { // Asks for more nuts than North has; the bolts line comes first. // Each {"bolt", 3} is one Line: an item and a quantity. const std::vector<inv::Line> too_many_nuts{{"bolt", 3}, {"nut", 5}}; try_transfer("line by line, not enough nuts", &inv::Warehouse::send_line_by_line, too_many_nuts, false); try_transfer("send, not enough nuts", &inv::Warehouse::send, too_many_nuts, false);
// Enough of everything, but the record cannot be written. const std::vector<inv::Line> fine{{"bolt", 3}, {"nut", 2}}; std::cout << '\n'; try_transfer("line by line, audit fails", &inv::Warehouse::send_line_by_line, fine, true); try_transfer("by copy, audit fails", &inv::Warehouse::send_by_copy, fine, true); try_transfer("send, audit fails", &inv::Warehouse::send, fine, true);
// South has no nut entry yet, so send must prepare one. std::cout << '\n'; try_transfer("send, nothing fails", &inv::Warehouse::send, {{"bolt", 3}, {"nut", 4}}, false);}line by line, not enough nuts failed: not enough nut North: bolt 7, nut 4 South: bolt 4, nut 0send, not enough nuts failed: not enough nut North: bolt 10, nut 4 South: bolt 1, nut 0
line by line, audit fails failed: audit store unavailable North: bolt 7, nut 2 South: bolt 4, nut 2by copy, audit fails failed: audit store unavailable North: bolt 10, nut 4 South: bolt 1, nut 0send, audit fails failed: audit store unavailable North: bolt 10, nut 4 South: bolt 1, nut 0
send, nothing fails recorded: North -> South: 3 bolt 4 nut North: bolt 7, nut 0 South: bolt 4, nut 4Reading the output:
- Not enough nuts. Line by line moves the 3 bolts and then
throws: North has 7 and South 4, with no record.
sendthrows in its check step, and nothing has moved. - Audit fails. Line by line has moved everything and cannot
record it, which breaks T3.
send_by_copyandsendthrow from the audit with both warehouses as they were. - Nothing fails. One record, every line moved, and South gains a
nutentry it did not have before, from the prepared node.
Testing every failure point
Section titled “Testing every failure point”Tests with a failing audit store and a short count check the failures you can cause on purpose:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false. LLD_CHECK_EQ(actual, expected) does the same// for actual == expected, and prints both values when they differ.// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception. They come from the site's small test header,// lld_test.hpp.//// Helpers defined earlier in this file and in recording_audit.hpp:// Pair: North with 10 bolts and 4 nuts, South with 1 bolt and no nuts.// too_many_nuts: 3 bolts, then 5 nuts (North has only 4).// RecordingAudit keeps every entry in `entries`; FailingAudit always// throws std::runtime_error("audit store unavailable").// Several tests build a second Pair, `before`, set up the same way, and// compare with it: equal afterwards means the failed call changed// nothing.
// The success case: every count moves and exactly one record is written.// South gets a nut entry it did not have.LLD_TEST(send_moves_every_line_and_records_it_once) { Pair p; RecordingAudit audit; p.north.send(p.south, {{"bolt", 3}, {"nut", 4}}, audit); LLD_CHECK_EQ(p.north.count("bolt"), 7); LLD_CHECK_EQ(p.north.count("nut"), 0); LLD_CHECK_EQ(p.south.count("bolt"), 4); LLD_CHECK_EQ(p.south.count("nut"), 4); LLD_CHECK(audit.entries == std::vector<std::string>{"North -> South: 3 bolt 4 nut"});}
// The bolts line could be met, the nuts line cannot: strong means even// the bolts stay where they were, and nothing is recorded.LLD_TEST(send_changes_nothing_when_a_later_line_cannot_be_met) { Pair p; const Pair before; RecordingAudit audit; LLD_CHECK_THROWS(p.north.send(p.south, too_many_nuts, audit), std::invalid_argument); LLD_CHECK(p.north == before.north && p.south == before.south); LLD_CHECK(audit.entries.empty());}
// Every check passes, but the record cannot be written: nothing moves.LLD_TEST(send_changes_nothing_when_the_audit_fails) { Pair p; const Pair before; FailingAudit audit; LLD_CHECK_THROWS(p.north.send(p.south, {{"bolt", 3}}, audit), std::runtime_error); LLD_CHECK(p.north == before.north && p.south == before.south);}
// Two lines of 3 nuts each are checked as 6, more than North's 4. Checked// one at a time, each would pass.LLD_TEST(send_adds_up_lines_for_the_same_item_before_checking) { Pair p; const Pair before; RecordingAudit audit; LLD_CHECK_THROWS(p.north.send(p.south, {{"nut", 3}, {"nut", 3}}, audit), std::invalid_argument); LLD_CHECK(p.north == before.north && p.south == before.south);}
// South is given the largest int number of nuts, so adding even one more// would overflow: send must refuse before changing North. The last two// checks show that a quantity of 0 and a send to the same warehouse are// refused too.LLD_TEST(send_refuses_a_count_that_would_not_fit) { Pair p; p.south.receive("nut", std::numeric_limits<int>::max()); const Warehouse north_before = p.north; RecordingAudit audit; LLD_CHECK_THROWS(p.north.send(p.south, {{"nut", 1}}, audit), std::overflow_error); LLD_CHECK(p.north == north_before); LLD_CHECK_THROWS(p.north.send(p.south, {{"nut", 0}}, audit), std::invalid_argument); LLD_CHECK_THROWS(p.north.send(p.north, {{"nut", 1}}, audit), std::invalid_argument);}
// The copy-and-swap version: a failed line and a failed audit both leave// the real warehouses as they were, and a call that succeeds does move// the bolts (South goes from 1 to 4).LLD_TEST(send_by_copy_changes_nothing_when_anything_fails) { Pair p; const Pair before; RecordingAudit recording; FailingAudit failing; LLD_CHECK_THROWS(p.north.send_by_copy(p.south, too_many_nuts, recording), std::invalid_argument); LLD_CHECK_THROWS(p.north.send_by_copy(p.south, {{"bolt", 3}}, failing), std::runtime_error); LLD_CHECK(p.north == before.north && p.south == before.south); p.north.send_by_copy(p.south, {{"bolt", 3}}, recording); LLD_CHECK_EQ(p.south.count("bolt"), 4);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What the basic guarantee does and does not promise. The nuts line// fails after the bolts have moved: the change stays (not strong), but// the total is still 10 + 4 + 1 = 15 (valid), and nothing was recorded.LLD_TEST(line_by_line_leaves_earlier_lines_moved_but_keeps_the_total) { Pair p; RecordingAudit audit; LLD_CHECK_THROWS(p.north.send_line_by_line(p.south, too_many_nuts, audit), std::invalid_argument); LLD_CHECK_EQ(p.north.count("bolt"), 7); // the first line moved LLD_CHECK_EQ(p.south.count("bolt"), 4); LLD_CHECK_EQ(p.north.total() + p.south.total(), 15); LLD_CHECK(audit.entries.empty()); // and nobody recorded it}Memory allocation is harder: it almost never fails in a test. The
example’s second test program replaces the global operator new
with one that can be told to fail on a chosen call:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How many more allocations may succeed before one fails. 0 means "fail// the next one", and -1 means "never fail". It is a plain global, read// and written without a lock, so this only works in a single-threaded// program. The unnamed namespace keeps it private to this file.namespace {int countdown = -1; // -1: never fail} // namespace
void fault::fail_after(int allocations) noexcept { countdown = allocations; }void fault::stop() noexcept { countdown = -1; }bool fault::armed() noexcept { return countdown >= 0; }
// Replaces the global operator new for this test program only.// Defining a function with exactly this signature replaces the standard// library's version when the program is linked, so every `new` in the// program, including the allocations inside std::string and std::map,// comes here. Step by step:// 1. If the countdown has reached 0, this is the call to fail: disarm// (set -1, so later calls work) and throw std::bad_alloc, as a real// out-of-memory failure would.// 2. Otherwise count this call down, if a failure is armed.// 3. Get the memory from std::malloc. A size of 0 is asked as 1,// because malloc(0) may return a null pointer, and operator new must// return a real pointer even for 0 bytes. If malloc itself fails,// throw, as the standard operator new does.void* operator new(std::size_t size) { if (countdown == 0) { countdown = -1; throw std::bad_alloc(); } if (countdown > 0) --countdown; if (void* memory = std::malloc(size == 0 ? 1 : size)) return memory; throw std::bad_alloc();}
// Memory from malloc must go back through free, so the matching// operator delete is replaced too, in both of its usual forms (the second// is told the size, which free does not need).void operator delete(void* memory) noexcept { std::free(memory); }void operator delete(void* memory, std::size_t) noexcept { std::free(memory); }Then a loop runs the transfer once per allocation: make the first allocation fail, then the second, and so on, until a run gets through with no failure. After each failure it compares both warehouses with copies taken before:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Runs the transfer once for each allocation it makes, making that one// allocation fail, until a run makes no allocation fail and so succeeds.// `send` is a pointer to one of Warehouse's three send functions (the// Send type above), so the same loop tests each version. The result// counts the failure points, how many of them left everything unchanged,// and whether every failure kept the total stock.Outcome fail_each_allocation(Send send) { Outcome outcome; // `for (int n = 0;; ++n)` has no condition: it repeats until the // `return` below. Run n lets the first n allocations succeed and makes // allocation number n + 1 fail. for (int n = 0;; ++n) { // A fresh setup on every run, made before the failure is armed, so // these allocations are never the ones that fail. Warehouse north("North"); Warehouse south("South"); north.receive("bolt", 10); north.receive("nut", 4); south.receive("bolt", 1); const Warehouse north_before = north; const Warehouse south_before = south; const std::vector<Line> lines{{"bolt", 3}, {"nut", 2}}; // nut is new to south RecordingAudit audit;
bool failed = false; fault::fail_after(n); // arm: n allocations succeed, then one fails try { // Calls the member function that `send` points at, on north. // `.*` joins an object and a pointer to a member function; the // brackets are needed because a call binds more tightly. (north.*send)(south, lines, audit); } catch (const std::bad_alloc&) { failed = true; } // armed() turns false once the failure has been thrown, so // `reached` says whether allocation number n + 1 happened at all. const bool reached = !fault::armed(); fault::stop(); // disarm, so the checks below can allocate safely // If the call succeeded, LLD_CHECK(!reached) makes sure that is // because it made no more than n allocations, not because it caught // the failure itself. Then runs 0 to n - 1 have failed each of its // allocations once, and the loop ends. if (!failed) { LLD_CHECK(!reached); // it succeeded, so no failure was reached and swallowed LLD_CHECK_EQ(south.count("nut"), 2); return outcome; } // The call threw: compare both warehouses and the audit with how // they were before. Equal is what the strong guarantee promises. ++outcome.failure_points; if (north == north_before && south == south_before && audit.entries.empty()) { ++outcome.unchanged; } // 15 = 10 bolts + 4 nuts in North + 1 bolt in South. Keeping it is // the least the basic guarantee must do. if (north.total() + south.total() != 15) outcome.totals_kept = false; }}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// For each version, run the loop above. `failure_points > 0` proves the// loop really made some allocation fail; without it, a version that// allocated nothing would pass without testing anything. Strong: every// failure point left everything unchanged. &Warehouse::send is a pointer// to the member function, passed as the Send argument.LLD_TEST(send_keeps_the_strong_guarantee_whichever_allocation_fails) { const Outcome outcome = fail_each_allocation(&Warehouse::send); LLD_CHECK(outcome.failure_points > 0); LLD_CHECK_EQ(outcome.unchanged, outcome.failure_points);}
LLD_TEST(send_by_copy_keeps_the_strong_guarantee_whichever_allocation_fails) { const Outcome outcome = fail_each_allocation(&Warehouse::send_by_copy); LLD_CHECK(outcome.failure_points > 0); LLD_CHECK_EQ(outcome.unchanged, outcome.failure_points);}
// Basic but not strong: every failure kept the total, and at least one// failure left a change behind.LLD_TEST(line_by_line_keeps_only_the_basic_guarantee) { const Outcome outcome = fail_each_allocation(&Warehouse::send_line_by_line); LLD_CHECK(outcome.totals_kept); // basic: still valid LLD_CHECK(outcome.unchanged < outcome.failure_points); // not strong}- For
sendandsend_by_copy, every failure point leaves both warehouses unchanged and nothing recorded. That is the strong guarantee, checked at each allocation the call really makes, with this standard library. - For
send_line_by_line, every failure keeps the total (basic), and at least one failure leaves a change behind (not strong). - The loop does not hard-code how many allocations there are. That number depends on the standard library and the build, so a test that expected an exact count would break for reasons that have nothing to do with the design.
How this code works: fail_each_allocation, run by run
Each pass of the loop is one complete run of the transfer, with its own fresh warehouses, built before the failure is armed so that setting up never fails.
- Arm.
fault::fail_after(n)lets the nextnallocations succeed and makes the one after fail. On run 0 the very first allocation inside the call fails; on run 1 the second; and so on. - Run. The call
(north.*send)(south, lines, audit)runs whichever version was passed in. If the chosen allocation is reached,operator newthrowsstd::bad_alloc, and thecatchsetsfailed. - Disarm.
fault::stop()turns failures off, so the checks that follow can allocate freely. - Judge. If the call threw, the run is one more failure point. It counts as unchanged only if both warehouses equal the copies taken before and the audit holds no entry. The loop also notes whether the total stock is still 15.
- Stop. When
nreaches the number of allocations the call makes, no failure is reached and the call succeeds. The loop checks that no failure was reached and caught inside the call, and that South now has its 2 nuts, and returns.
So if a call makes, say, eight allocations, runs 0 to 7 each fail a
different one, and run 8 succeeds. The real number depends on the
standard library, which is why the loop finds it rather than being
told. The three tests then compare the counts: for a strong version,
unchanged must equal failure_points; for the line-by-line version,
some failure must have left a change.
The limits of this test:
- It replaces only the single-object, non-aligned
operator new. The standard’s own array andnothrowforms call that one, so they are counted too; the aligned forms are not, and this code does not use them. The audit’s failure is tested separately; a failing comparison or copy of a user type would need its own test double. - The replacement counter is a plain global, so it only works in a single-threaded test program, and it is kept in its own program so that it cannot affect other tests.
- It runs one input. A different transfer may allocate in other places; the guarantee comes from the code’s structure, and the test checks that structure on one path.
The class at a glance
Section titled “The class at a glance”class inv::Warehouse
invariant: every count is at least zero
Data members
void commit(Warehouse& to, wanted, new_items) noexcept;std::string name_;std::map<Sku, int> stock_;
Member functions
Warehouse& operator=(Warehouse other) noexcept;copy-and-swapfriend void swap(Warehouse& a, Warehouse& b) noexcept;int count(const Sku& sku) const noexcept;void receive(const Sku& sku, int quantity);strongvoid send_line_by_line(Warehouse& to, lines, AuditSink& audit);basicvoid send_by_copy(Warehouse& to, lines, AuditSink& audit);strongvoid send(Warehouse& to, lines, AuditSink& audit);strong
interface (abstract class) inv::AuditSink
may throw; cannot be undone
Member functions
virtual void record(const std::string& entry) = 0;
class inv::Line
a struct
Member functions
Sku sku;int quantity;
Choosing a guarantee
Section titled “Choosing a guarantee”- Every function: basic. No leaks, no broken invariants. RAII, checking before changing, and changing the safe side first, as the line-by-line version does, usually get there.
- Strong when the requirements say all or nothing, or when a caller cannot sensibly continue from a partly changed state: a transfer, a configuration reload, an undo, an edit the user can cancel. Do not make everything strong; it costs copies or preparation, and many operations, such as appending to a log, are fine with basic.
- Nothrow for the building blocks: destructors, swap, moves, commit steps, and simple reads. Other code builds its strong guarantees out of these.
- Document it. Write the guarantee in the header next to the function, as the example does. A caller cannot see it from the signature.
Common mistakes
Section titled “Common mistakes”- Changing first, checking later. Every check belongs before the first change.
- Forgetting allocation. “This cannot fail” is rarely true of code that adds to a container or builds a string.
- Calling the irreversible step last. It belongs just before a commit that cannot fail.
- Two steps that can fail and cannot be undone, hoping both work. Design a compensation or an outbox instead.
noexcepton a function that allocates, or missing on a move or swap that cannot throw.- Catching and ignoring.
catch (...) {}turns a failure into a silent wrong result. Undo and rethrow, or report it. - Throwing from a destructor. Destructors are
noexceptby default; a throw ends the program, and during another exception it always does.
When the requirements change
Section titled “When the requirements change”- “Also notify the shipping system.” That is a second step that cannot be undone. Record the transfer and an outgoing message together, then send the message later, with retries; see the outbox on Transaction and persistence boundaries and Idempotency, retries, and duplicate handling.
- “Warehouses live in different databases.” No C++ ordering gives the strong guarantee across two stores. Use a transaction in one store and a message to the other, or a sequence of steps with compensations. A two-phase commit between the stores exists, but it needs both stores to support it and is rarely the right choice.
- “Several threads send at once.” The strong guarantee does not
stop another thread from reading during
commit. The transfer needs a lock on both warehouses, taken in a fixed order to avoid deadlock, covered on the planned page on deadlocks and lock ordering. - “Partial transfers are allowed, and the result says which lines moved.” Then basic is the requirement, not a defect. Return the lines that moved, and record what actually happened.
Exercise
Section titled “Exercise”Exercise: Upgrade to the strong guarantee
A delivery adds several lines to one warehouse at once. This version
is written with receive, which has the strong guarantee for one line:
This is illustrative and was not compiled.
// Adds every line to this warehouse. receive(sku, quantity) adds one// line, with the strong guarantee for that one line; the loop calls it// once per line, in order.void Warehouse::receive_all(const std::vector<Line>& lines) { for (const Line& line : lines) receive(line.sku, line.quantity);}- Which guarantee does
receive_allgive? Describe an input for which a failure leaves the warehouse changed. - Rewrite it to give the strong guarantee without copying the whole warehouse. Say which steps can throw and which cannot.
- A colleague suggests
try { … } catch (...) { /* subtract the lines already added */ throw; }. When does that work, and why is the prepared version simpler here?
Show the explained answer
-
Basic. Each line is all or nothing, but the loop is not. With lines
{"bolt", 5}, {"nut", 0}, the bolts are added and then the second line throwsstd::invalid_argument. With{"bolt", 5}for a new item followed by a line whose count would overflow, the same happens withstd::overflow_error. Running out of memory while adding a new item in a later line leaves the earlier lines added. -
Check, prepare, then commit, the same shape as
send. This was compiled as a member of a copy of the example’sWarehousewith GCC 11.4 and Clang 14, and run with a short check under AddressSanitizer:// Strong guarantee: check, prepare, commit, the same shape as send.void Warehouse::receive_all(const std::vector<Line>& lines) {// Check. The total per item goes in a local map, so two lines of// the same item are checked together.std::map<Sku, int> wanted; // check: may throw, changes nothingfor (const Line& line : lines) {check_line(line); // a quantity must be positiveint& sum = wanted[line.sku]; // starts at 0 for a new itemsum = add_checked(sum, line.quantity);}// Would any count overflow? The result is not needed, only the// check.for (const auto& [sku, quantity] : wanted) add_checked(count(sku), quantity);// Prepare. Make, on the side, an entry of 0 for each item this// warehouse lacks: these are the only allocations the commit needs.std::map<Sku, int> new_items; // prepare: may throw, changes nothingfor (const auto& [sku, quantity] : wanted) {if (!stock_.contains(sku)) new_items.emplace(sku, 0);}// Commit. merge relinks the prepared nodes without allocating; then// every item is present, and each addition was checked above.stock_.merge(new_items); // commit: nothing below can throwfor (const auto& [sku, quantity] : wanted) stock_.find(sku)->second += quantity;}The checks, the two local maps, and their allocations can throw; all of them happen before
stock_changes.merge,find, and the additions cannot throw, the additions because they were checked for overflow. There is no step that cannot be undone, so no audit ordering is needed. -
Undoing works if every undo cannot fail and the code knows exactly what was done. Subtracting a count cannot fail, but the undo must also erase entries that were created for new items, or it leaves zero-count entries that were not there before. To know what to undo, it must keep a list of the lines and new entries already added, and building that list can itself allocate and throw. The prepared version has nothing to undo, because nothing the caller can see changes until the commit.
Summary
Section titled “Summary”- The basic guarantee keeps invariants after a failure; the strong guarantee keeps the whole state; the nothrow guarantee means the operation cannot fail. Every function needs basic.
- Find every step that can throw, including allocation, before choosing an order.
- Copy-and-swap turns basic into strong, at the cost of a copy,
using a
noexceptswap. Takingoperator=’s argument by value gives a strong copy assignment the same way. - Prepare, record, commit: do everything that can fail on objects nobody can see, then the one step that cannot be undone, then only steps that cannot fail.
- An operation can have at most one step that both can fail and cannot be undone. More need compensation or an outbox.
noexceptis a promise that ends the program if broken. It belongs on destructors, swaps, moves, commit steps, and reads, and not on anything that allocates.- Fault injection, such as making each allocation fail in turn, tests failure paths that would otherwise never run.