C++ 为什么';难道没有调用析构函数吗?
例如,我使用RAII和C++ 为什么';难道没有调用析构函数吗?,c++,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(){
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();
}
#包括
使用名称空间std;
void g(){
投掷5枚;
}
等级兰德{
公众:
~Rand(){
cout来自:
堆栈展开
当控制流向上移动调用堆栈时,将调用析构函数
对于已构造自动存储持续时间的所有对象,但不是
但已销毁,,因为在中输入了相应的try块
他们的建造师完成的相反顺序
代码中没有相应的try块,因此不会调用析构函数,程序也会终止
如果将程序更改为:
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) {}
试试看
{
auto p=std::make_unique();//应调用dtor
Rand*r=new Rand();//不应调用dtor
cout a来自:
堆栈展开
当控制流向上移动调用堆栈时,将调用析构函数
对于已构造自动存储持续时间的所有对象,但不是
但已销毁,,因为在中输入了相应的try块
他们的建造师完成的相反顺序
代码中没有相应的try块,因此不会调用析构函数,程序也会终止
如果将程序更改为:
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) {}
试试看
{
auto p=std::make_unique();//应调用dtor
Rand*r=new Rand();//不应调用dtor
因为没有catch块,所以可能无法执行展开。请尝试在main中捕获g的异常。@NicholasWilson,那么如果没有展开,会发生什么?它不应该自动展开以尝试查找catch块吗?在应用程序因异常而完成执行后,操作系统将释放内存,但不会执行析构函数。不是吗是吗?确实,它试图找到一个catch块,但您还没有提供。展开(可能)从搜索catch块开始(您还没有提供您的OS/arch/libc,平台可以以不同的方式实现)。因为没有捕获块,所以可能无法执行解缠。请尝试在main中捕获g的异常。@NicholasWilson,那么如果没有解缠发生,会发生什么?它不应该自动解缠以尝试查找捕获块吗?在应用程序因异常而完成执行后,操作系统将释放内存,但不会执行析构函数。不是吗?INDED,它确实试图找到一个catch块,但您还没有提供。展开(可能)从搜索catch块开始(您还没有提供您的OS/arch/libc,平台可以以不同的方式实现)。