现在的位置: 首页 > 综合 > 正文

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

2013年10月09日 ⁄ 综合 ⁄ 共 1387字 ⁄ 字号 评论关闭
--------------  测试程序-----------------------------

#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。
   是不是如此,没有测试,因为我觉得肯定是这样的。 

抱歉!评论已关闭.