其他分享
首页 > 其他分享> > c – 为什么在此代码中没有调用复制构造函数

c – 为什么在此代码中没有调用复制构造函数

作者:互联网

那么为什么不在“const Integer operator(const Integer& rv)”函数中调用Copy构造函数.是因为RVO.如果是,我需要做些什么来防止它?

#include <iostream>

using namespace std;

class Integer {
    int i;

public:
    Integer(int ii = 0) : i(ii) {
        cout << "Integer()" << endl;
    }

    Integer(const Integer &I) {
        cout << "Integer(const Integer &)" << endl;
    }

    ~Integer() {
        cout << "~Integer()" << endl;
    }

    const Integer operator+(const Integer &rv) const {
        cout << "operator+" << endl;
        Integer I(i + rv.i);
        I.print();
        return I;
    }

    Integer &operator+=(const Integer &rv) {
        cout << "operator+=" << endl;
        i + rv.i;
        return *this;
    }

    void print() {
        cout << "i: " << i << endl;
    }
};

int main() {
    cout << "built-in tpes:" << endl;
    int i = 1, j = 2, k = 3;
    k += i + j;
    cout << "user-defined types:" << endl;
    Integer ii(1), jj(2), kk(3);
    kk += ii + jj;

}

我确实收到错误如果我将注释掉复制构造函数.我希望在运算符返回时调用复制构造函数.以下是该计划的输出

built-in tpes:
user-defined types:
Integer()
Integer()
Integer()
operator+
Integer()
i: 3 // EXPECTING Copy Constructor to be called after this
operator+=
~Integer()
~Integer()
~Integer()
~Integer()

解决方法:

Is it because of RVO. If Yes what do I need to do to prevent it?

是.但由于编译器因为Return Value Optimization而未被调用.

如果您正在使用GCC,请使用-fno-elide-constructors选项来避免它.

GCC 4.6.1 manual说,

-fno-elide-constructors

The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.

标签:c,copy-constructor
来源: https://codeday.me/bug/20190926/1820620.html