Exception safety
- C++ course
- Advanced
- Lesson 74/83
- 5 min
Learn exception safety guarantees.
Exception safety guarantees
The exception safety guarantee of a function describes how it preserves program state when an exception is thrown. There are three main guarantees: basic, strong and nothrow.
Basic guarantee: after an exception the object stays in a valid state, no resource leaks. Strong guarantee: the operation either completes or the object stays exactly as it was (rollback). Nothrow guarantee: the function never throws; destructors and swap are like this. These three form the skeleton of robust code design.
Strong guarantee: copy-and-swap
The classic way to provide the strong guarantee is the copy-and-swap technique: first take a copy of the object, make the change on the copy, then swap with swap.
Example: void add_item(vector<string>& v, const string& item) { vector<string> copy = v; copy.push_back(item); v.swap(copy); }. push_back may throw when memory is full; in that case v is untouched. swap is nothrow, so the last step cannot fail. This way either the addition completes or v stays exactly as it was.
Practice Write add_item with the strong guarantee
Write the add_item function with copy-and-swap: std::vector<std::string> copy = v;, copy.push_back(item);, v.swap(copy);. In main create std::vector<std::string> v{"a", "b"};, call add_item(v, "c") and print v.size().
Starter code
#include <iostream>
#include <vector>
#include <string>
// Write the add_item function with copy-and-swap
int main() {
// Create a vector, call it and print the size
return 0;
}Sample solution
#include <iostream>
#include <vector>
#include <string>
void add_item(std::vector<std::string>& v, const std::string& item) {
std::vector<std::string> copy = v;
copy.push_back(item);
v.swap(copy);
}
int main() {
std::vector<std::string> v{"a", "b"};
add_item(v, "c");
std::cout << v.size();
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each guarantee to its description
| Term | Meaning |
|---|---|
basic |
Valid state |
strong |
Rollback |
nothrow |
Never throws |
swap |
Nothrow swap |
2 nothrow swap
v.____(copy);
v.swap(copy);
Explanation: swap is nothrow and is the last step of the strong guarantee.
3 In which scenario is the strong guarantee provided?
- When the function never throws
- When the object stays as it was on exception (rollback) Correct answer
- When the object is always corrupted
- When the exception is swallowed
Explanation: Strong guarantee: the operation either completes or the object stays as it was via rollback.