Copy constructor not called when returning from overloaded + operator to overloaded = operator

164 views Asked by At

Consider the following code:

#include <iostream>
using namespace std;
class loc 
{
    int longitude, latitude;
    public:
        loc() {}
        loc(int lg, int lt) 
        {
            longitude = lg;
            latitude = lt;
        }
        loc(const loc& l)
        {
            cout << "a" << endl;
        }
        loc operator = (loc op2)
        {
            longitude = op2.longitude;
            latitude = op2.latitude;
            return *this;
        }
        loc operator+(loc op2);
};
loc loc::operator+(loc op2) {
    loc temp;
    temp.longitude = op2.longitude + longitude;
    temp.latitude = op2.latitude + latitude;
    return temp;
}
int main()
{
    loc ob1(10, 20), ob2( 5, 30);
    ob1 = ob1 + ob2;
    return 0;
}

On compiling this program using the command: g++ file.cpp, the output was:

a
hello

And then compiling this program using the command: g++ -fno-elide-constructors file.cpp, the output was:

a
a
a
hello

My question is:

In the first case, why are two copy constructors elided?

Which copy constructors are elided anyways? Is there a different mechanism for = operator or + operator

EDIT

I know how the correct assignment operator or copy constructor should look like. Please answer why two copy constructors are elided in the above case rather than correcting the assignment operator.

1

There are 1 answers

5
Alan Stokes On BEST ANSWER

One elided copy is the return from op+. RVO allows the result to be constructed directly in the final destination, omitting temp altogether. The elided copy is from temp.

The second elided copy is passing the result of op+, which is a temporary, to op=. Instead it arranges for the result of op+ to be directly constructed in the op2 parameter. This isn't RVO, just normal elision of temporaries.