#include <iostream>
#include <vector>
#include <stdexcept>
class Resource {
public:
Resource(int id) : id_(id) {
std::cout << "Resource " << id_ << " acquired\n";
}
~Resource() {
std::cout << "Resource " << id_ << " released\n";
}
private:
int id_;
};
class StrongExceptionGuarantee {
public:
void operation(int n) {
std::vector<Resource> resources;
for (int i = 0; i < n; ++i) {
resources.push_back(Resource(i));
if (i == 2) {
throw std::runtime_error("Simulated error");
// Exception thrown here
// Stack unwinding begins:
// 1. vector's destructor is called
// 2. vector's destructor calls Resource destructor for each element
// 3. Each Resource prints its "released" message
// 4. vector is fully destroyed
// 5. Exception continues propagating
}
}
}
};
int main() {
StrongExceptionGuarantee seg;
try {
seg.operation(5);
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}