我很困惑为什么在抛出excpetion时会调用两次destrctor,以及它们被称为??
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是输出
constructor called
destrctor called
handle all exception
destuctor is called
Run Code Online (Sandbox Code Playgroud)
但是当我添加了复制构造函数时,它从未调用过但是析构函数只调用一次,所以发生了什么?
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
constructor called
handle all exception
destrctor called
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
875 次 |
| 最近记录: |