C++中的异常处理(求教:catch中的向上类行转化)

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的子类呢?有高手的话,麻烦给回复一段。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值