c ++ copy constructor和operator = not invoked

时间:2014-02-27 05:11:30

标签: c++ copy-constructor

我正在对复制构造函数和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;
}

我使用命令g++ -o test -g3 test.cpp在linux amd64上使用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

似乎在getCopy函数中都没有调用复制构造函数和operator =。我错过了什么或者我误解了什么吗?请帮忙。提前谢谢。

更新: 感谢@Mike Seymour,现在我知道这是复制省略的问题。当我用g++ -o test test.cpp -fno-elide-constructors禁用g ++ copy elision时,输出看起来更合理:

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

4 个答案:

答案 0 :(得分:0)

getCopy()函数中的CopyC()将调用默认构造函数

CopyC c2 = c1将调用复制构造函数

参考Copy constructor vs. return value optimization

标准规定不需要使用复制构造函数 - 参见12.8 / 15节:

15每当使用复制构造函数复制临时类对象,并且此对象和副本具有相同的cv-unqualified类型时,允许实现将原始对象和副本视为引用相同的两种不同方式对象并且根本不执行副本,即使类复制构造函数或析构函数具有副作用。

答案 1 :(得分:0)

在getCopy()函数中,您正在调用默认构造函数CopyC()。对于您编写的复制构造函数,您应该在getCopy()函数中调用CopyC(c1)

答案 2 :(得分: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;
}

答案 3 :(得分:0)

某些编译器提供称为“名称返回值”的优化。

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

}

代码在编译器中可能看起来像这样:

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

}

所以,在getCopy函数中都没有调用复制构造函数和operator =。 我希望它有所帮助。

相关问题