How to implement guide with dynamic memory allocation and handling safety in c++ class with std::unique_ptr
I'm dealing with I've been banging my head against this for hours. I'm working with an scenario with exception safety in my C++ class that uses `std::unique_ptr` for dynamic memory management. The class is designed to manage a buffer, and I want to ensure that if an exception occurs during the initialization of the buffer, the memory is released properly without leaking. Here's a simplified version of my class: ```cpp #include <iostream> #include <memory> #include <stdexcept> class Buffer { public: Buffer(size_t size) : data_(new int[size]), size_(size) { if (size == 0) { throw std::invalid_argument("Size must be greater than zero"); } // Simulating a potential failure during initialization if (size > 1000) { throw std::runtime_error("Buffer size too large"); } // Initialize buffer with values for (size_t i = 0; i < size_; ++i) { data_.get()[i] = i; } } void print() { for (size_t i = 0; i < size_; ++i) { std::cout << data_.get()[i] << " "; } std::cout << std::endl; } private: std::unique_ptr<int[]> data_; size_t size_; }; ``` When I test this code with a large size, I receive the following behavior: ``` terminate called after throwing an instance of 'std::runtime_error' what(): Buffer size too large Aborted ``` My concern is that even if the exception occurs during the construction of the `Buffer` class, the memory allocated by `std::unique_ptr` should be handled automatically. However, the program terminates instead of a clean exit. I've also tried wrapping the instantiation in a try-catch block: ```cpp try { Buffer buf(2000); // This should throw } catch (const std::exception& e) { std::cerr << "Caught an exception: " << e.what() << std::endl; } ``` Yet, the behavior remains the same. Can someone explain why this is happening and how I can ensure proper resource management without causing abrupt termination? Am I missing something regarding how exceptions are propagated or handled in this context? Iām using C++17 with g++ version 9.3.0. For context: I'm using C++ on macOS. Has anyone else encountered this? For context: I'm using C++ on CentOS.