2014-02-27 64 views
0

我正在做複製構造函數和運算符=的一些測試,但我得到了一些奇怪的結果。C++複製構造函數和運算符=未調用

這裏是我的兩個測試文件test.h和TEST.CPP:

test.h

class CopyC { 
public: 
    CopyC() { 
     cout << ">> In Default Constructor" << endl; 
    } 
    CopyC(const CopyC &other) { 
     cout << ">> In Copy Constructor" << endl; 
    } 
    ~CopyC() { 
     cout << ">> In Deconstructor" << endl; 
    } 

    CopyC& operator=(const CopyC &other) { 
     cout << ">> In Operator =" << endl; 
     return *this; 
    } 

    CopyC getCopy() { 
     cout << ">> In getCopy" << endl; 
     cout << "return CopyC()" << endl; 
     return CopyC(); 
    } 
}; 

TEST.CPP

#include "test.h" 

int main() { 
    cout << "CopyC c1" << endl; 
    CopyC c1; 
    cout << "CopyC c2 = c1.getCopy()" << endl; 
    CopyC c2 = c1.getCopy(); 

    cout << "<< Finish" << endl; 
} 

我使用海合會4.6.3 linux amd64,命令g++ -o test -g3 test.cpp。的./test輸出是

CopyC c1 
>> In Default Constructor 
CopyC c2 = c1.getCopy() 
>> In getCopy 
return CopyC() 
>> In Default Constructor 
<< Finish 
>> In Deconstructor 
>> In Deconstructor 

看來,無論是拷貝構造函數,也沒有運營商=在該getCopy函數調用。我錯過了什麼或者我誤解了某些東西?請幫忙。提前致謝。

更新: 感謝@Mike西摩,現在我知道,這是複製省略的問題。當我停用G ++複製省略與g++ -o test test.cpp -fno-elide-constructors,輸出看起來更合理的:

CopyC c1 
>> In Default Constructor 
CopyC c2 = c1.getCopy() 
>> In getCopy 
return CopyC() 
>> In Default Constructor 
>> In Copy Constructor 
>> In Deconstructor 
>> In Copy Constructor 
>> In Deconstructor 
<< Finish 
>> In Deconstructor 
>> In Deconstructor 
+2

正確回答你的問題,不要做任何相關的問題嗎?這會讓我大吃一驚。 – chris

回答

0

CopyC()在getCopy()函數將調用默認的構造函數

CopyC c2 = c1將調用拷貝構造函數

參考Copy constructor vs. return value optimization

該標準說明不需要使用複製構造函數 - 參見12.8節/ 15節:

15無論何時使用複製構造函數複製臨時類對象,並且此對象和副本具有相同的cv-unqualified類型,都允許實現將原始對象和副本視爲指向同一對象的兩種不同方式即使類拷貝構造函數或析構函數有副作用,也不會執行任何拷貝。

+0

這並不能解釋爲什麼copyC2 = c1.getCopy();不會調用複製構造函數**。幸運的是,有很多重複的問題解釋複製elision。 –

0

在getCopy()函數中,您調用了默認構造函數CopyC()。對於您編寫的拷貝構造函數,您應該在getCopy()函數中調用CopyC(c1)

0

看來該錯誤可能在getCopy()函數中。

CopyC getCopy() { 
    cout << ">> In getCopy" << endl; 
    cout << "return CopyC()" << endl; 
    return CopyC(); 
} 

getCopy預計要返回CopyC類的一個對象,而是功能CopyC()返回不返回任何東西本身。 解決方案是創建一個CopyC對象並返回它。

CopyC getCopy() { 
    cout << ">> In getCopy" << endl; 
    cout << "return CopyC()" << endl; 
    CopyC copy; 
    return copy; 
} 
+0

'CopyC'是一種類型,所以當用作表達式時,'CopyC()'是一個臨時實例。 – chris

+0

哦,好的,謝謝你爲我清理這件事,因爲我對此並不滿意 –

0

一些編譯器提供了一種稱爲「名稱返回值」的優化。

CopyC getCopy() { 
cout << ">> In getCopy" << endl; 
cout << "return CopyC()" << endl; 
return CopyC(); 

}

的代碼或許看起來像這樣在編者:

void getCopy(CopyC &__result){ 
..... 
__result.CopyC::CopyC(); 

}

所以,無論是拷貝構造函數,也沒有運營商=在getCopy函數被調用。 我希望它有幫助。

相關問題