C++ exception throw和catch的时候,发生了什么

202 篇文章 4 订阅 ¥19.90 ¥99.00
本文详细分析了C++中抛出和捕获异常时对象生命周期的变化,揭示了在使用默认构造、拷贝构造以及析构函数过程中,临时对象的创建和销毁过程。通过实例展示了在按值传递异常时,构造函数和析构函数调用的次数,以及为何推荐使用引用捕获异常以减少不必要的拷贝操作。
摘要由CSDN通过智能技术生成
--------------  测试程序-----------------------------

#include <stdio.h>
#include <string.h>
#include <iostream>

int gi = 0;

class CA
{
public:
    CA(): mi(gi) { cout<< "CA" <<mi << " default constructor "<<endl;  gi++; }
    CA(const CA &oa) { mi = gi; cout<< "CA" <<mi << " copy constructor" <<endl; gi++;}
    ~CA() { cout<< "CA" <<mi << " destructor" <<endl; }
private:
    int mi;   
};


void fun()
{
    CA   oa;
    throw oa;
}

int main()
{
    try
    {
     cout<< "in try block "<<endl;
     fun(); 
    }
    catch( CA oa)
    {
        cout<<"catch" <<endl;
        oa.fun();
    }
    cout<<"after catch"<<endl;
    getchar();

   }

--------------  输出结果-----------------------------

in try block
CA0 default constructor
CA1 copy constructor
CA0 destructor
CA2 copy constructor
catch
CA2 fun() is called
CA2 destructor
CA1 destructor
after catch

--------------  结果分析-----------------------------

在throw oa的时候,发生了:
  编译器生成一个临时CA对象,并调用CA的copy constructor,类似于: CA oa_temp( oa );
  然后oa对象出来生存期,oa的destructor被调用。
 同时 oa_temp被作为catch的参数传递到catch 块中。
 在catch的时候,因为采用的by value传递参数,所以编译器又要生成一个临时CA对象,并发生一次copy constructor,类似于: CA oa_temp2 (  oa_temp  );
 在catch块中,使用的其实是oa_temp2,这个可以从结果“CA2 fun() is called”来判断出。
 最后,在出了catch块后,先是oa_temp2被析构,然后是oa_temp。
 
 从上可以,在by value throw 和by value catch的情况下,会发生
     3次构造函数调用,1次default constructor,2次copy constructor
     3次析构函数调用
 
--------------  心得 -----------------------------
   c++书籍中建议: throw by value , and catch by reference.
   如果catch by reference,我认为会发生2次构造函数调用,2次析构函数调用。少了一次copy constructor和一次对应的destructor。
   是不是如此,没有测试,因为我觉得肯定是这样的。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值