『C/C++』G++的命名返回值优化 -- NRVO

原文地址:G++的命名返回值优化 -- NRVO


今天在运行C++ primer中一段程序的时候,没有打印复制构造函数的信息,代码如下:

        

[cpp]  view plain copy
  1. class Exmpl {  
  2. public:  
  3.         Exmpl() {cout << "Exmple()" << endl;}  
  4.         Exmpl(const Exmpl&) {cout << "Exmple(const Exmpl&)" << endl;}  
  5.         Exmpl & operator = (const Exmpl &rhs)  
  6.         {  
  7.                 cout << "operator = (const Exmple&rhs)" << endl;  
  8.                 return *this;  
  9.         }  
  10.   
  11.         ~Exmpl()  
  12.         {  
  13.                 cout << "~Exmpl()" << endl;  
  14.         }  
  15. };  
  16.   
  17. void func1(Exmpl obj)  
  18. {  
  19. }  
  20.   
  21. void func2(Exmpl &obj)  
  22. {  
  23. }  
  24.   
  25. Exmpl func3()  
  26. {  
  27.         Exmpl obj;  
  28.         return obj;  
  29. }  
  30.   
  31. int main(int argc, char **argv)  
  32. {  
  33.         Exmpl eobj;  
  34.         func1(eobj);  
  35.         func2(eobj);  
  36.   
  37.         eobj = func3();  
  38. }  


         按照我的分析,输出结果如下:

         

[cpp]  view plain copy
  1. Exmple()  
  2. Exmple(const Exmpl&)  
  3. ~Exmpl()  
  4. Exmple()  
  5. <span style="color:#ff0000;">Exmple(const Exmpl&)  
  6. ~Exmpl()  
  7. </span>operator = (const Exmple&rhs)  
  8. ~Exmpl()  
  9. ~Exmpl()  


         可是我电脑上的输出如下(我使用的是g++ 4.0.2)

       

[cpp]  view plain copy
  1. Exmple()  
  2. Exmple(const Exmpl&)  
  3. ~Exmpl()  
  4. Exmple()  
  5. operator = (const Exmple&rhs)  
  6. ~Exmpl()  
  7. ~Exmpl()  


        查阅资料,原来是g++默认启用了命名返回值优化,named return value optimizatio - NRVO

        加上-fno-elide-constructors后,就可以关掉NRVO了。

        g++的手册说:

[cpp]  view plain copy
  1. -fno-elide-constructors  
  2.           The C++ standard allows an implementation to omit creating a  
  3.           temporary which is only used to initialize another object of the  
  4.           same type.  Specifying this option disables that optimization, and  
  5.           forces G++ to call the copy constructor in all cases.   


        我在Visual Studio 2005下运行上面的程序,输出和没有加-fno-elide-constructors的g++编译出来的程序一样。这说明Visual Studio 2005默认是不会开启该优化选项的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值