我在复制构造函数和operator=上做了一些测试,但是我得到了一些奇怪的结果。
下面是我的两个测试文件-- 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;
}我在linux amd64上用命令g++ -o test -g3 test.cpp使用gcc 4.6.3。./test的输出是
CopyC c1
>> In Default Constructor
CopyC c2 = c1.getCopy()
>> In getCopy
return CopyC()
>> In Default Constructor
<< Finish
>> In Deconstructor
>> In Deconstructor似乎在operator=函数中既没有调用复制构造函数,也没有调用getCopy。是我错过了什么还是我误解了什么?请帮帮忙。提前谢谢。
update:感谢@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发布于 2014-02-27 05:15:49
函数中的CopyC()函数将调用默认构造函数
CopyC c2 = c1将调用复制构造函数
请参阅Copy constructor vs. return value optimization
标准规定不需要使用复制构造函数--见12.8/15节:
15每当使用复制构造函数复制临时类对象,且该对象和副本具有相同的cv非限定类型时,就允许实现将原始类和副本视为引用同一对象的两种不同方式,而根本不执行副本,即使类复制构造函数或析构函数有副作用。
发布于 2014-02-27 05:20:36
在getCopy()函数中,调用CopyC()是默认构造函数。对于您编写的复制构造函数,应该在getCopy()函数中调用getCopy。
发布于 2014-02-27 05:22:16
看起来错误可能在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;
}https://stackoverflow.com/questions/22059529
复制相似问题