I wrote this program in two different compilers and I got two different results:
#include <iostream>
using namespace std;
class Point {
public:
int n;
Point() { n = 0; }
Point operator= (Point p) { return *this; }
Point(const Point& p) { cout<<"copy\n"; }
~Point() { cout<<"Destruct\n"; }
};
int main() {
Point p1, p2, p3;
p1 = p2 = p3;
return 0;
}
Compiler 1:
copy
copy
copy
Destruct
Destruct
Destruct
Destruct
Destruct
Destruct
Compiler 2:
copy
copy
Destruct
copy
Destruct
Destruct
Destruct
Destruct
Destruct
I know that some compilers optimize the pass/return by value of an object from a function by not calling the copy constructor. Is this the reason for the difference between the two results?
More importantly, why is the copy constructor called twice for the p2 = p3 part of the code but only once for p1 = ... ?
I don't do much OO programming using C++, that is why I am confused with this simple question. I really appreciate some hints
Your assignment operator should return Point &
not Point
, and it should take the parameter as a reference, too :
Point &operator = (const Point &p) { return *this; }
Otherwise, unnecessary copying may occur. Most likely, one copy is created going in to the assignment operator, then the returned value is copied to both p2
and p1
.