⚙️Go deeper — read the bookStack unwinding & exception safety— runnable code & full walkthrough →

cpp core · advanced

Exception-Safety Guarantees

Exception safety classifies what happens to program state when an operation throws. No guarantee: state may be corrupted and resources leaked. Basic guarantee: no leaks and all invariants hold, but the value may be unspecified. Strong guarantee: commit-or-rollback — if it throws, state is exactly as before (a transaction). Nothrow: the operation is noexcept and cannot throw. The copy-and-swap idiom achieves the strong guarantee by doing all throwing work on a temporary copy, then committing with a noexcept swap; RAII delivers the basic guarantee automatically.

🔑 Key line

Four exception-safety guarantees (weakest->strongest): no guarantee, basic (valid, no leak), strong (commit-or-rollback), nothrow (noexcept). copy-and-swap is the standard way to get the strong guarantee; RAII gives the basic guarantee for free.

The code

// The four exception-safety guarantees, weakest -> strongest:
// 1. no guarantee : a throw may corrupt/leak (avoid)
// 2. basic : no leak, object stays valid (value unspecified)
// 3. strong : commit-or-rollback - state unchanged if it throws
// 4. nothrow : marked noexcept, cannot throw
// Strong guarantee via copy-and-swap:
T& operator=(T other) { // copy may throw - but only the temp
swap(*this, other); // noexcept swap commits atomically
return *this; // old state freed by temp's dtor
}

What this lesson walks through

  1. 01
  2. 02
  3. 03
  4. 04
  5. 05
  6. 06
  7. 07

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Exception-Safety Guarantees and 100+ animated C++ interview lessons.

← Previous
Exceptions & Stack Unwinding
Next →
C++ keywords by version — a specifier & attribute timeline