2010-05-07 126 views
4

我有这样的代码拷贝构造函数在C++

#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

我假设你想知道行Test t3=t1+t2;

编译器被允许优化复制建设了。见http://www.gotw.ca/gotw/001.htm

+0

mkj:Excellent Link!.. :) – 2012-01-11 10:10:10

4

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

barricada ~$ g++ -o test test.cpp -O0 -fno-elide-constructors 
barricada ~$ ./test 
copy 
30 
copy 
134515065 
-1217015820 
20 
10