C++ – Why Copy Constructor is Not Called

c++copy-constructor

So why is Copy constructor not being invoked in "const Integer operator+(const Integer &rv)" function. Is it because of RVO. If Yes what do I need to do to prevent it?

#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;

}

I do get an error If I'll comment out copy constructor. I'm expecting copy constructor to be called when operator+ returns. Following is the output of the program

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()

Best Answer

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

Yes. But it didn't get called because of Return Value Optimization by the compiler.

If you're using GCC, then use -fno-elide-constructors option to avoid it.

GCC 4.6.1 manual says,

-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.

Related Question