为什么没有调用析构函数?

时间:2017-08-10 08:19:04

标签: c++

我正在使用RAII并使用try / catch来避免内存泄漏。这是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();
}

由于stackunwinding和RAII与std::unique_ptr一起使用,不应该将堆栈分配对象的析构函数作为throw / {{的基本保证。 1}}因为抛出异常?

1 个答案:

答案 0 :(得分:5)

来自throw

  

堆栈展开

     

当控制流向上移动调用堆栈时,将调用析构函数   对于构建了自动存储持续时间的所有对象,但不是   然后销毁,因为输入了相应的try-block ,in   完成其构造函数的逆序。

您的代码中没有相应的try-block,因此不会调用析构函数并终止程序。

如果您将程序更改为:

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) {}

您将看到,调用包含在unique_ptr中的对象的析构函数。