Bana
Bana

Reputation: 117

Why doesn't the destructor get called?

I am using RAII and using try/catch to not leak memory for example. Here is an implementation in C++:

#include <iostream>
using namespace std;

void g(){
    throw 5;
}

class Rand{
public:
    ~Rand(){
        cout << "Randomm Destructor called" << endl;
    }
    int a = 17;
};

void f(){
    auto p = std::make_unique<Rand>(); //Should call dtor
    Rand* r = new Rand(); //Shouldnt call dtor
    cout << p->a << endl; //Prints 17
    g();
    cout << "This never executes" << endl;
}


int main(){
    f();
}

Due to stackunwinding and using RAII with the std::unique_ptr, shouldn't the destructors for stack allocated objects be called as a basic guarantee to throw/try since an exception is being thrown?

Upvotes: 1

Views: 88

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

From throw:

Stack unwinding

As the control flow moves up the call stack, destructors are invoked for all objects with automatic storage duration constructed, but not yet destroyed, since the corresponding try-block was entered, in reverse order of completion of their constructors.

There is no corresponding try-block in your code, so no destructors are called and the program is terminated.

If you change the program as:

try
{
    auto p = std::make_unique<Rand>(); //Should call dtor
    Rand* r = new Rand(); //Shouldnt call dtor
    cout << p->a << endl; //Prints 17
    g();
    cout << "This never executes" << endl;
}
catch (int) {}

you will see, that the destructor for the object which is wrapped into unique_ptr is called.

Upvotes: 4

Related Questions