try、catch调用过程中构造、析构函数问题,请指教。
#include <exception>
#include <iostream.h>
#include <stdlib.h>
class Up
{
public:
Up() {cout<<"Up con"<<endl;}
~Up() {cout<<"~Up don"<<endl;}
};
class fit
{
public:
fit() {cout<<"fit con"<<endl;}
~fit() {cout<<"~fit don"<<endl;}
};
void g();
void f(int iExcept) throw(Up, fit);
void My_Unexcepted();
void main()
{
//set_unexpected(My_Unexcepted);
for(int iL = 1; iL <= 3; iL++)
{
try
{
f(iL);
}
catch(Up)
{
cout<<"Up caught"<<endl;
}
catch(fit)
{
cout<<"fit caught"<<endl;
}
catch(...)
{
cout<<"Unknown exception"<<endl;
}
}
}
void f(int iExcept)
{
switch(iExcept)
{
case 1:throw Up();
case 2:throw fit();
}
g(); //use unknown exception
}
void g()
{
//longjmp(Koera, 1);
throw 30;
}
void My_Unexcepted()
{
cout<<"unexcepted exception thrown"<<endl;
exit(1);
}
执行结果为什么构造函数调用一次,而析构函数调用两次,这是怎么回事?
结果:
Up con
~Up don
Up caught
~Up don
fit con
~fit don
fit caught
~fit don
Unknown exception