随笔-59  评论-36  文章-0  trackbacks-0
在<C++编程思想>2th中文版 第12.3.3.2节“返回值优化”中说,对于处理“return Integer(left.i + left.i);”这种的返回时,编译器直接在目的内存中创建,且因为不是创建局部对象,故可直接调用普通构造函数,而不需要复制构造函数;但,对于

Integer temp;
return temp;

这样的返回值形式,是需要调用复制构造函数来在目标内存中创建对象的。

我在VC2005中试了如下的小函数,

X f()
{
    X one(
5);
    
//return one; //因为VC中默认情况下debug模式优化被禁止;release模式优化可用,所以在release模式下直接将one的定义目标内存中;debug则是调用复制构造在目标内存中构造
    
//return X(4); // release & debug 都直接在目标内存中构造对象
}

int main()
{
   X test 
= f();
}

对于,
Integer temp;
return temp;
这种形式,在VC2005中,如果没有禁用优化,则不要求复制构造函数可访问,也就是说复制构造函数都不会被调用。
但标准中说:“Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions must be respected as if the temporary object was created. [ Example: even if the copy constructor is not called, all the semantic restrictions, such as accessibility (clause 11), shall be satisfied.]”,所以还是保留复制构造函数的可访问性吧。

P.S. : 后来了解到VC中(或者说标准允许)对命名对象的返回采用“命名返回值优化(NRVO)”来进行优化,但是对于这种优化只有在某些编译器选项开启后才得以实现,至少VC是这样的。

2009.6.18 更新
posted on 2009-05-24 23:11 zhaoyg 阅读(950) 评论(0)  编辑 收藏 引用 所属分类: C/C++学习笔记

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理