我很困惑为什么在抛出异常时会调用两次析构函数,调用的是哪一点??
#include <iostream>
using namespace std;
class base
{
public:
base(){cout<<"constructor called"<<endl;}
~base(){cout<<"destructor called"<<endl;}
};
void fun()
{
throw base(); //<=- Create temp obj of base, and throw exception
}
int main()
{
try
{
fun();
}
catch(...)
{
cout<<"handle all exception"<<endl;
}
}
输出如下
constructor called
destrctor called
handle all exception
destuctor is called
但是当我添加复制构造函数时,它从未调用过,但析构函数只调用了一次所以发生了什么????
#include <iostream>
using namespace std;
class base
{
public:
base(){cout<<"constructor called"<<endl;}
~base(){cout<<"destructor called"<<endl;}
base (base &obj){cout<<"copy constructor called"<<endl;}
};
void fun()
{
throw base(); //<=- Create temp obj of base, and throw exception
}
int main()
{
try
{
fun();
}
catch(...)
{
cout<<"handle all exception"<<endl;
}
}
输出:
constructor called
handle all exception
destrctor called
最佳答案
编译器可以根据需要多次复制您的异常对象。析构函数被调用两次,因为有一个拷贝。
关于c++ - 为什么抛出异常时析构函数调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6456587/