Exception Safety Guarantees in C++
Exception safety grades how code behaves when throws interrupt it: no-throw (never fails — swaps, moves, destructors), strong (commit-or-rollback — failed operations leave state untouched), basic (no leaks, invariants hold, but state may change), and none (all bets off). RAII delivers basic safety almost free; strong safety takes deliberate patterns like copy-and-swap.
Design rule: mutating operations should offer at least basic, widely-used ones strong, and destructors plus swaps no-throw unconditionally. Document the grade per function — callers writing transactional code need to know what failures leave behind.
No-throw: can't fail
Swaps, moves, destructors, and deallocations must never throw — mark them noexcept to promise it.
Strong: all or nothing
Copy-and-swap: build the new state aside, then commit with a non-throwing swap — observers see old or new, never half.
Basic: no leaks, valid state
RAII members guarantee this baseline — resources freed, invariants intact, even if values changed mid-operation.
Destructors never throw
A throwing destructor during unwinding calls std::terminate — catch everything inside destructors, always.
#include <iostream>#include <vector>#include <string> int main() { std::vector<std::string> v{"a"}; try { v.reserve(1000000000ULL * 1000ULL); } catch (const std::bad_alloc&) { std::cout << "kept " << v.size() << std::endl; } return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.