throw/catch究竟会不会复制一个对象?
More Effective C++上面说,要在catch语句里面使用引用,避免对象拷贝和阶段。
我用GCC和VC2010测试了一番,发现不论是否使用引用,似乎都不存在throw对象的拷贝-->似乎throw对象直接被放在了catch的空间里面,用不用&都是没有额外的拷贝。
但是这一来就无法解释,如果我在catch里面使用基类对象名,throw一个子类对象的时候,好像是会被截断。
但是,既然没有生成一个基类对象,从子类对象做截断拷贝(没有看到额外的拷贝函数调用),那么这个信息丢失又是如何发生的呢? 测试结果让我非常的疑惑啊:
#include<stdio.h>struct base{ int i; base(){ printf("base ctor\n"); i=2; }};struct child: base{ child(){ printf("child ctor\n"); j=3; } int j;};int main(void){ try{ throw child(); }catch(base b){ int*pi=(int*)&b; printf("catch by value, c.i=%d,c.j=%d\n",pi[0],pi[1]); } try{ throw child(); }catch(base& b){ int*pi=(int*)&b; printf("catch by ref, c.i=%d,c.j=%d\n",pi[0],pi[1]); } try{ throw child(); }catch(child& c){ int*pi=(int*)&c; printf("catch by ref, c.i=%d,c.j=%d\n",pi[0],pi[1]); } return 0;}