织梦CMS - 轻松建站从此开始!

罗索

Try throw catch 的一个问题

jackyhwei 发布于 2011-04-21 19:19 点击:次 
这篇讨论有效的揭露了try, throw , catch 的本质的工作方法。
TAG:

关于http://groups.google.com/group/comp.lang.c++/browse_thread/thread/649c39f943a65a36/e8d328a4a547ff36?lnk=st&q=catch+(const+Mammal+%26m)+&rnum=1#e8d328a4a547ff36

这篇讨论有效的揭露了try, throw , catch 的本质的工作方法。

源代码如下:

  1. #include <iostream> 
  2. using namespace std; 
  3. class Mammal 
  4. public
  5.  Mammal() 
  6.  { 
  7.   cout << "Constructing Mammal @ " << this << endl; 
  8.  } 
  9.  Mammal(const Mammal& source) 
  10.  { 
  11.   cout << "Copy Constructing Mammal @ " << this << " from " << 
  12.    &source << endl; 
  13.  } 
  14.  ~Mammal() 
  15.  { 
  16.   cout << "Destructing Mammal @ " << this << endl; 
  17.  } 
  18.  virtual const char* MyType() const 
  19.  { 
  20.   return "Mammal"
  21.  }
  22. };
  23.  
  24. class Cat : public Mammal 
  25. public
  26.  Cat() 
  27.  { 
  28.   cout << "Constructing Cat @ " << this << endl; 
  29.  } 
  30.  Cat(const Cat& source) 
  31.  { 
  32.   cout << "Copy Constructing Cat @ " << this << " from " << 
  33.    &source << endl; 
  34.  } 
  35.  ~Cat() 
  36.  { 
  37.   cout << "Destructing Cat @ " << this << endl; 
  38.  } 
  39.  
  40.  virtual const char* MyType() const 
  41.  { 
  42.   return "Cat"
  43.  }
  44. };
  45.  
  46. int main(int argc, char *argv[]) 
  47.  try 
  48.  { 
  49.   Cat fluffy; 
  50.   Mammal& fluffyRef = fluffy; 
  51.   throw fluffyRef; 
  52.  } 
  53.  catch (const Mammal &m) 
  54.  { 
  55.   cout << "Caught a " << m.MyType() << endl; 
  56.   return 0; 
  57.  } 
  58.   
  59.  cout << "Nothing Caught" << endl; 
  60.  return 0; 

输出:

Constructing Mammal @ 0012FF50
Constructing Cat @ 0012FF50
Copy Constructing Mammal @ 0012FE60 from 0012FF50
Destructing Cat @ 0012FF50
Destructing Mammal @ 0012FF50
Caught a Mammal
Destructing Mammal @ 0012FE60

对这个例子我的感悟:

1.throw 的用法, 它将抛出某个具体的object(异常类),这个类将被catch所捕捉。由于fluffRef是一个Mammal的reference,但是它的instance 其实是一个cat。但是在throw抛出的时候,throw其实跟不管instance 的type,它只是根据抛出对象申明的type 拷贝构造出一个新的临时的对象以作为异常对象。所以,Throw 抛出的时候,不看对象instance的type,而是看这个当前申明的类型。
2. 如果我们将代码改成
 try
 {
  Cat fluffy;
  Cat& fluffyRef = fluffy;
  throw fluffyRef;
 }
这个时候,当然throw 的是cat。 注意,这个地方throw调用 Mammal和默认构造函数和Cat的拷贝构造函数,不是我所想象的是基类也是调用拷贝构造函数。

(weili_2007)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201104/11266.html]
本文出处:CSDN博客 作者:weili_2007
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容