Search code examples
c++exceptionshared-ptrsmart-pointers

Object in smart pointer is not deleted after stack unwinding


I wrote a small program, to check the difference between creating shared_ptr via new and make_shared() function in case of exceptions. I read everywhere that via make_shared() it is an exception-safe.

But the interesting thing about both these cases is that the destructor in both cases is not called after stack unwinding? Am I missed something? Thanks in advance.

#include <iostream>
#include <memory>

class Car
{
public:
    Car() { cout << "Car constructor!" << endl; throw std::runtime_error("Oops"); }
    ~Car() { cout << "Car destructor!" << endl; }
};

void doProcessing()
{
//    std::shared_ptr<Car> sp(new Car());
    std::shared_ptr<Car> sp2 = std::make_shared<Car>();
}

int main()
{
    try
    {
        doProcessing();
    }
    catch(...)
    {
    }
    return 0;
}

Solution

  • What object?

    The only object in a smart pointer here did not actually complete construction, because its constructor threw. It doesn't exist.

    You don't need smart pointers to demonstrate this. Just throw from any constructor and you'll see that the destructor body is not invoked.