您的位置:首页 > 编程语言 > C语言/C++

C++ 三种抛出异常方法的跟踪

2008-07-31 09:50 387 查看
记得看书上说值传递时异常会被构造三次,引用传递会被构造两次,指针传递才会只构造一次,今天试了一个,却只有值传递只被构造两次,其它两种方式只构造一次,在Cygwin和VC++ 9.0上都试了,结果一样,测试代码如下:

#include
#include

using std::cout;
using std::string;

class MyException
{
public:
MyException(const string& name, int no)
: m_name(name), m_no(no)
{
cout< }

MyException(const MyException& old)
:m_name(old.m_name), m_no(old.m_no)
{
cout< }

~MyException( void )
{
cout< }
string m_name;
int m_no;

};

int main(int argc, char* argv[])
{
try{
throw MyException("value exception",1 );
}
catch(MyException ex)
{
cout<<"caught exception:"< }

try{
throw MyException("reference exception", 2);
}
catch(MyException& ex)
{
cout<<"caught exception:"< }

try{
MyException* pe = new MyException("pointer exception", 3);
throw pe;
}
catch(MyException* pe){
cout<<"caught exception:"<m_name< delete pe;
}
}

测试结果:

1:value exception : MyException::MyException( )
1:value exception is copied
caught exception:value exception
1 :MyException::~MyException( )
1 :MyException::~MyException( )
2:reference exception : MyException::MyException( )
caught exception:reference exception
2 :MyException::~MyException( )
3:pointer exception : MyException::MyException( )
caught exception:pointer exception
3 :MyException::~MyException( )

还需要再证实一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐