赞
踩
记得看书上说值传递时异常会被构造三次,引用传递会被构造两次,指针传递才会只构造一次,今天试了一个,却只有值传递只被构造两次,其它两种方式只构造一次,在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( )
还需要再证实一下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。