example3_basic_exception_safety_with_RAII.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
#include <iostream>
#include <memory>
#include <stdexcept>

class Resource {
public:
    Resource() { std::cout << "Resource acquired" << std::endl; }
    ~Resource() { std::cout << "Resource released" << std::endl; }
    void use() { std::cout << "Resource used" << std::endl; }
};

class ResourceUser {
private:
    std::unique_ptr<Resource> resource;

public:
    ResourceUser() : resource(std::make_unique<Resource>()) {}

    void performOperation() {
        resource->use();
        // Simulating an operation that might throw
        throw std::runtime_error("Operation failed");
    }
};

int main() {
    try {
        ResourceUser user;
        user.performOperation();
    } catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
Back to exception_safety