The noexcept Specifier in C++
noexcept declares a function cannot throw — part of its type and contract. Violating it calls std::terminate immediately (no unwinding), which sounds harsh but lets the compiler optimize harder and the library choose faster paths: vector grows with moves instead of copies exactly when the move constructor is noexcept.
Mark what cannot fail (swaps, moves, destructors, simple accessors); leave throwing operations unmarked rather than lying. Conditional noexcept(noexcept(expr)) propagates guarantees through templates — the standard library is built on this pattern.
A contract, enforced by terminate
void f() noexcept; promises no exceptions escape — a throw inside ends the program via std::terminate, no handler consulted.
Unlocks move optimizations
std::vector relocates with moves only if they are noexcept (else copies, to preserve strong safety) — one keyword decides the strategy.
Destructors are implicitly noexcept
Destructors default to noexcept(true) — declaring one noexcept(false) is legal but almost always a design error.
Conditional propagation
noexcept(noexcept(x.swap(y))) mirrors an expression's guarantee — templates forward no-throw-ness instead of guessing it.
#include <iostream>#include <utility> void safe_swap(int& a, int& b) noexcept { int t = a; a = b; b = t;} int main() { int x = 1, y = 2; safe_swap(x, y); std::cout << x << ", " << y << std::endl; std::cout << noexcept(safe_swap(x, y)) << 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.