Garbage appears in the vector after entering the result of the operator

I have an object with an operator defined as follows:

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 directly assigned the result of adding 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 this through a variable, everything will be as expected.

vector<P> u(1);
P q = p1 + p2;
u[0] = q; // u[0] contains correct value.

What could be causing this behavior? What is the difference between these two cases?

+3
source share
2 answers

You are returning a temporary link. This is a bad idea, since the temporary goes beyond the scope at the end of the function (in this case, the function operator+). Declare your operator as:

P operator +(const P &rhs) const

instead.

+10
source

How do you see

P& operator +(const P &rhs) 
{
    return P(x + rhs.x, y + rhs.y, z + rhs.z);
}

, operator +.

, , , .

,

++ 11 move, , , .

+3

All Articles