构造中的异常

如果构造函数中抛出异常会发生什么情况?

  • 构造过程立即停止
  • 当前对象无法生成
  • 析构函数不会被调用
  • 对象所占用的空间立即收回

建议

  • 不要再构造函数中抛出异常
  • 当构造函数可能产生异常时,使用二阶构造模式
#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()
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值