【问题标题】:After I disable g++ return value optimization,Why the last call of constructor for temporary reference?禁用g++返回值优化后,为什么最后调用构造函数进行临时引用?
【发布时间】:2012-08-06 02:54:07
【问题描述】:

我使用以下命令编译 c++ 代码以禁用返回值。
g++ -fno-elide-constructors rvoptimazation.cpp -o test
但是 ./test 的输出是
10
10
10
13
0xbfdf0020
13
我对构造函数的最后一次调用感到困惑。谁能解释在运算符*中返回后哪一行代码将调用构造函数?提前致谢。

#include<iostream>    

using namespace std;  

class Rational{  
public:  
    Rational(int x ,int y){  
        _a = x;  
        _b = y;  
        cout << __LINE__ << endl;  
    }  
    Rational(Rational const &t){  
        cout << __LINE__ << endl;  
    }  
    Rational operator*(Rational const &t){  
        Rational re = Rational(_a * t._a ,_b * t._b);  
        cout << &re << endl;  
        return re;  
        //return *this;  
    }  
    Rational get()  
    {  
        return *this;  
    }  
public:  
    int _a ,_b;  
};  

int main()  
{  
    Rational r1(1 ,2);  
    Rational r2(2 ,3);  
    r1 * r2;  
 // cout << &r3 << endl;  
}  

【问题讨论】:

    标签: g++ compiler-optimization


    【解决方案1】:

    operator*按值返回,所以必须构造返回的对象。语句return re 调用复制构造函数来执行此操作。

    我觉得Return value optimization的解释很清楚。

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多