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

class Risky {
public:
    Risky(bool throwException) {
        if (throwException) {
            throw std::runtime_error("Construction failed");
        }
        std::cout << "Risky object constructed" << std::endl;
    }
    ~Risky() {
        std::cout << "Risky object destructed" << std::endl;
    }
};

void unsafeCreation(bool throwException) {
    try {
        std::shared_ptr<Risky> ptr(new Risky(throwException));
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
}

void safeCreation(bool throwException) {
    try {
        auto ptr = std::make_shared<Risky>(throwException);
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
}

int main() {
    std::cout << "Unsafe creation:" << std::endl;
    unsafeCreation(true);

    std::cout << "\nSafe creation:" << std::endl;
    safeCreation(true);

    return 0;
}
Back to std_make_shared