c++ - 为什么在此代码中未调用复制构造函数

标签 c++ copy-constructor

那么为什么在“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;

}

如果我注释掉复制构造函数,我确实会收到错误消息。我期待在 operator+ 返回时调用复制构造函数。以下是程序的输出

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++ - 为什么在此代码中未调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779827/

相关文章:

c++ - 将指向结构的指针转换为具有较少数量字段的另一种结构类型

c++ - 如何在gradle native 项目中包含二进制库?

c++ - 将一张 map 的内容附加和替换到另一张 map ?

c++ - 在 _wsystem 中转义引号

c++ - 为什么这里调用的是 Copy Constructor 而不是普通的 Constructor 和重载的赋值运算符?

c++ - 为非静态引用成员类写入 `operator=`

c++ - QWebView等待加载

c++ - BigInt C++ 和正确的复制构造函数?

C++'98 - 将基类转换为派生类

c++ - 如何将基类的私有(private)成员复制到派生类的复制构造函数中