C++的try关键字会产生一个独立的栈,try中间的函数和产生的异常对象都在上面,此栈只有在try catch块完成后,才能获得释放。
语法不多谈,举几个例子
class B
{
public:
B()
{
cout << this << "B init" << endl;
}
B(B& b)
{
cout << this << "B copy" << endl;
}
virtual ~B()
{
cout << this << "B destory" << endl;
}
};
void func()
{
throw B();
}
void main()
{
try
{
func();
}
catch(B b)
{
cout << "C catched" << endl;
}
}
执行结果:
0012FF14B init
0012FF6CB copy
C catched
0012FF6CB destory
0012FF14B destory
可见抛出的B()产生在栈上,并且在catch的时候,调用拷贝构造函数形成了一个dummy。两个对象都在catch块结束的时候出栈,析构。
修改catch(B b)为 catch(B & b)
执行结果:
0012FF14B init
C catched
0012FF14B destory
可见b用的是对象的引用。
当然也可以用指针判断,修改throw B();为 throw &B(); catch(B b)为catch(B* b)
执行结果:
0012FF04B init
0012FF04B destory
C catched
可见使用指针和使用引用类似。
我们尝试把B()产生在堆上,修改throw &B() 为 throw new B();
执行结果:
00372A90B init
C catched
可见try catch块的出栈无法触发堆上对象的析构。需要在每个catch里面 delete b; 所以这种类似Java的语法还是少用的好。
一个比较费解的问题,用父类可以catch子类:
class C
{
};
class B : public C
{
public:
B()
{
cout << this << "B init" << endl;
}
B(B& b)
{
cout << this << "B copy" << endl;
}
virtual ~B()
{
cout << this << "B destory" << endl;
}
};
void func()
{
throw &B();
}
void main()
{
try
{
func();
}
catch(C *c)
{
cout << "C catched" << endl;
}
}
结果为:
0012FF04B init
0012FF04B destory
C catched
奇怪的地方在于我的工程并没有打开RTTI的支持,B和C类也没有实现虚函数,那么指向B的指针是怎么在运行态的时候得知B是C的子类呢?有高手的话,麻烦给回复一段。