我正在做複製構造函數和運算符=的一些測試,但我得到了一些奇怪的結果。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
正確回答你的問題,不要做任何相關的問題嗎?這會讓我大吃一驚。 – chris