4

我有这个代码

#include <iostream>
using namespace std;

class Test{
   public:
      int a;

      Test(int i=0):a(i){}
      ~Test(){
         cout << a << endl;
      }

      Test(const Test &){
         cout << "copy" << endl;
      }

      void operator=(const Test &){
         cout << "=" << endl;
      }

      Test operator+(Test& p){
         Test res(a+p.a);
         return res;
      }
};

int main (int argc, char const *argv[]){
   Test t1(10), t2(20);
   Test t3=t1+t2;
   return 0;
}

输出:

30
20
10

为什么这里不调用复制构造函数?

4

3 回答 3

11

这是一种称为返回值优化的特殊情况,其中允许编译器优化临时对象。

于 2010-05-07T10:11:50.050 回答
4

正如其他人所说,它只是优化对复制构造函数的调用,如果禁用这些优化会发生什么。

barricada ~$ g++ -o test test.cpp -O0 -fno-elide-constructors
barricada ~$ ./test
copy
30
copy
134515065
-1217015820
20
10
于 2010-05-07T10:14:05.650 回答
4

我想你想知道这条线Test t3=t1+t2;

允许编译器优化复制构造。请参阅http://www.gotw.ca/gotw/001.htm

于 2010-05-07T10:11:11.207 回答