2013-12-19 441 views
0
#include <iostream> 
using namespace std; 

class X 
{ 
public: 
    X() { cout<<"default constructor"<<endl; } 
    X(const X&) { cout<<"copy constructor"<<endl; } 
}; 

X test(X a) 
{ 
    X y = a; 
    return y; 
} 

int main() 
{ 
    X obj; 

    X obj1 = test(obj); 
    return 0; 
} 

輸出:拷貝構造函數叫錯

default constructor 
copy constructor 
copy constructor 

我已經編譯使用MinGW的編譯器。

但是,我認爲輸出是錯誤的。 複製構造函數在對象按值傳遞,按值返回或顯式複製時調用。 在上面的程序中,"copy constructor"必須被調用4次。

  1. test(obj)被調用,以obj複製到a
  2. X y = a被調用時,明確地複製。
  3. return y叫,y被複制到一個臨時對象,讓它成爲temp
  4. X obj1 = temp,明確地複製。

請糾正我。提供您的理由太..

+0

如果合適,請添加語言標籤。你還會得到自動的語法高亮;) – dyp

回答

1

這是(N)RVO的示例,又名命名的返回值優化。編譯器允許在下面的代碼的Elid到副本:

X test(X a) 
{ 
X y = a; 
return y; 
} 

如果你寫了這樣的事情,而不是:

X test(X a) 
{ 
X x = a; 
X y = a; 
return (true ? x : y); 
} 

(N)RVO將不適用。