- 论坛徽章:
- 0
|
20可用积分
本帖最后由 donet8 于 2012-03-23 16:07 编辑
More Effective C++上面说,要在catch语句里面使用引用,避免对象拷贝和阶段。
我用GCC和VC2010测试了一番,发现不论是否使用引用,似乎都不存在throw对象的拷贝-->似乎throw对象直接被放在了catch的空间里面,用不用&都是没有额外的拷贝。
但是这一来就无法解释,如果我在catch里面使用基类对象名,throw一个子类对象的时候,好像是会被截断。
但是,既然没有生成一个基类对象,从子类对象做截断拷贝(没有看到额外的拷贝函数调用),那么这个信息丢失又是如何发生的呢? 测试结果让我非常的疑惑啊:
- i#include"stdafx.h"
- struct base{
- int i;
- base(){
- printf("base ctor\n");
- i=2;
- }
- };
- struct child: base{
- child(){
- printf("child ctor\n");
- j=3;
- }
- int j;
- };
- using namespace std;
- int main(void){
- string s1="abc";
- string s2=s1;
- printf("%p,%p\n",s1.c_str(),s2.c_str());
- 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;
- }
- //默认已经开启了SEH,什么选项?
复制代码 VC和GCC的测试结果一样的,都是下面这样:
base ctor
child ctor
catch by value, c.i=2,c.j=-858993460
base ctor
child ctor
catch by ref, c.i=2,c.j=3
base ctor
child ctor
catch by ref, c.i=2,c.j=3
|
|