如果构造函数中抛出异常会发生什么情况?
- 构造过程立即停止
- 当前对象无法生成
- 析构函数不会被调用
- 对象所占用的空间立即收回
建议
- 不要再构造函数中抛出异常
- 当构造函数可能产生异常时,使用二阶构造模式
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test()" << endl;
throw 0;
cout << "Test(++)" << endl;//不会执行 抛出异常后构造过程立即停止
}
virtual ~Test() //析构函数没有被执行
{
cout << "~Test()" << endl;
}
};
int main(int argc, char *argv[])
{
Test* p = reinterpret_cast<Test*>(1);
try
{
p = new Test();
}
catch(...)
{
cout << "Exception..." << endl;
}
cout << "p = " << p << endl; //对象所占用的空间立即收回
return 0;
}
/*
Test()
Exception...
p = 0x1
*/
析构中的异常
- 避免在析构函数中抛出异常
- 析构函数中的异常将导致:对象所使用的资源完全无法释放
如果析构函数中抛出异常会发生什么情况?
导致terminate()函数被多次调用
#include <iostream>
#include <cstdlib>
#include <exception>
using namespace std;
void my_terminate()
{
cout << "void my_terminate()" << endl;
exit(1);
//abort();//强制结束当前的运行程序,不会调用析构函数
}
class Test
{
public:
Test()
{
cout << "Test()";
cout << endl;
}
~Test()
{
cout << "~Test()";
cout << endl;
throw 2;
}
};
int main()
{
set_terminate(my_terminate);
static Test t;
throw 1;
return 0;
}
/*
Test()
void my_terminate()
~Test()
void my_terminate()
*/