example2_weak_exception_guaranty.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <memory>
#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 WeakExceptionGuarantee {
private:
    std::unique_ptr<Resource> resource1;
    std::unique_ptr<Resource> resource2;

public:
    void operation() {
        resource1 = std::make_unique<Resource>(1);
        
        // Simulating some work that might throw
        if (rand() % 2 == 0) {
            throw std::runtime_error("Simulated error");
        }
        
        resource2 = std::make_unique<Resource>(2);
    }
};

int main() {
    WeakExceptionGuarantee weg;
    try {
        weg.operation();
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
Back to exceptions