How to Fix C++ Exception Safety Guarantee Violations
In this tutorial, you'll learn about How to Fix C++ Exception Safety Guarantee Violations. We cover key concepts, practical examples, and best practices.
C++ exception safety violations occur when an operation that throws leaves the program in an inconsistent state. The three guarantees are: no-throw (operations never throw), strong (commit or rollback), and basic (no resource leaks, valid state).
Quick Fix
Wrong
struct DataStore {
std::vector<int> data_;
bool ready_ = false;
void load() {
data_.resize(100);
ready_ = true; // if next line throws, ready_ is true but data_ is empty
loadFromNetwork(data_); // may throw
}
};
If loadFromNetwork throws, ready_ is true but data_ is empty, violating the basic guarantee.
Right
void load() {
std::vector<int> temp(100);
loadFromNetwork(temp);
data_ = std::move(temp); // swap or move after all risky operations
ready_ = true;
}
The strong guarantee: if anything throws, the object state is unchanged.
Fix for swap idiom
struct Widget {
std::vector<int> data_;
int config_;
void update(const std::vector<int>& newData, int newConfig) {
auto copy = data_; // copy
auto configCopy = config_;
copy.resize(newData.size());
std::copy(newData.begin(), newData.end(), copy.begin());
configCopy = newConfig;
data_.swap(copy); // nothrow swap
config_ = configCopy;
}
};
Fix for no-throw destructors
struct Resource {
~Resource() noexcept { // destructors are noexcept by default
// cleanup
}
};
Prevention
- Use the copy-and-swap idiom for the strong guarantee.
- Never let destructors throw (they are
noexceptby default). - Use RAII wrappers to prevent resource leaks on exceptions.
- Keep critical sections free of throwing operations.
- Use
std::moveafter the source is fully constructed.
DodaTech Tools
Doda Browser's C++ exception analyzer traces exception paths and detects guarantee violations. DodaZIP archives exception-safety code reviews. Durga Antivirus Pro detects exception safety issues that could cause denial of service.
Common Mistakes with exception safety
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world CPP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro