Exception Safety
Use exception-safe practices like smart pointers in C++ (std::unique_ptr
, std::shared_ptr
), which manage memory automatically even when exceptions occur.
4 Levels of Exception Safety
- No exception safety - If an exception is thrown - no guarantees about program state - object has invalid memory, memory is leaked, program crashes.
- Basic guarantee - if an exception is thrown - program is in a valid, but unspecified state. Ex: Class invariants are maintained, no memory is leaked.
- Strong guarantee - If an exception is thrown, the program reverts back to its state before the method was called. Ex:
vector::emplace_back
- Either it succeeds, or if exception is thrown, vector is in its prior state
- Nothrow guarantee - exceptions are never propagated outside of the function call - always does its job. Ex:
vector::size
givesnothrow
guarantee, always returns size of vector without fail.