#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;
}