简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM