The following code gives a different number of destructors when compiled on GCC and vc9. AFAIK when run on vc9 i get 5 destructors showing, which I understand. The + overloaded operator is called, and two object are created, when returned a temporary object is created. This makes destruction of 3 objects possible. When the overloaded = operator is called, one object is created and again a temporary one when returned. This sums it up to five destructs, not counting the three objects created at the start of main.
But when I compile on GCC I get 3.
Which leads me to guess that there isn’t a temporary object created when the function is terminated and returned ? or a question about different behavior between compilers. I simply do not know, and some clarification would be nice.
#include <iostream>
using namespace std;
class planetCord {
double x, y, z;
public:
planetCord() { x = y = z = 0; }
planetCord(double j, double i, double k) { x = j; y = i; z = k; }
~planetCord() { cout << "destructing\n"; }
planetCord operator+(planetCord obj);
planetCord operator=(planetCord obj);
void show();
};
planetCord planetCord::operator +(planetCord obj) {
planetCord temp;
temp.x = x + obj.x;
temp.y = y + obj.y;
temp.z = z + obj.z;
return temp;
}
planetCord planetCord::operator =(planetCord obj) {
x = obj.x;
y = obj.y;
z = obj.z;
return *this;
}
void planetCord::show() {
cout << "x cordinates: " << x << "\n";
cout << "y cordinates: " << y << "\n";
cout << "z cordinates: " << z << "\n\n";
}
int main() {
planetCord jupiter(10, 20, 30);
planetCord saturn(50, 100, 200);
planetCord somewhereDark;
jupiter.show();
saturn.show();
somewhereDark.show();
somewhereDark = jupiter + saturn;
jupiter.show();
saturn.show();
somewhereDark.show();
return 0;
}
GCC is implementing the “return value optimization” to skip temporaries. Set VC9 to Release mode and it’ll probably do the same.
If GCC is really good, it is seeing that
tempinsideoperator+will be default-initialized, just likesomewhereDark, and can just use a reference tosomewhereDarkdirectly if it tries to inline the function. Or it is seeing that the pass-by-value is useless and can instead pass-by-reference.