I have an object with an operator defined like this:
P& operator +(const P &rhs) {
return P(x + rhs.x, y + rhs.y, z + rhs.z);
}
It does not have custom copy or assignment operators.
After I assign directly the result of an addition inside the vector, garbage appears inside it.
P p1(1.0, 0.0, 0.0);
P p2(0.0, 0.0, 0.0);
vector<P> v(1);
v[0] = p1 + p2; // v[0] now contains garbage.
If I do it through a variable, everything is as expected.
vector<P> u(1);
P q = p1 + p2;
u[0] = q; // u[0] contains correct value.
What can be the reason for such behavior? What is the difference between the two cases?
You return a reference to a temporary. This is a bad idea, since the temporary goes out of scope at the end of the function (in this case, the
operator+function). Declare your operator as:instead.