G
Guest
The code below I suspect creates memory leaks:
In the main() in line "c += a + b;" when compiler runs "a + b" creates a new object.
After "c += 'new_object'"
we have an unreferenced object which created from "a + b" and not destroyed.
am I right?
What I can do to avoid this?
------------------------------
class Vector3D {
protected:
float _x, _y, _z;
public:
Vector3D(float x, float y, float z) : _x(x), _y(y), _z(z) {}
const Vector3D &operator+=(const Vector3D &a);
friend const Vector3D operator+(const Vector3D &a, const Vector3D &b);
};
const Vector3D &Vector3D:
perator+=(const Vector3D &a) {
_x += a._x; _y += a._y; _z += a._z; return *this;
}
const Vector3D operator+(const Vector3D &a, const Vector3D &b) {
return Vector3D(a._x + b._x, a._y + b._y, a._z + b._z);
}
void main() {
Vector3D a = Vector3D(1, 2, 3);
Vector3D b = Vector3D(4, 5, 6);
Vector3D c = Vector3D(0, 0, 0);
c += a + b;
}
In the main() in line "c += a + b;" when compiler runs "a + b" creates a new object.
After "c += 'new_object'"
we have an unreferenced object which created from "a + b" and not destroyed.
am I right?
What I can do to avoid this?
------------------------------
class Vector3D {
protected:
float _x, _y, _z;
public:
Vector3D(float x, float y, float z) : _x(x), _y(y), _z(z) {}
const Vector3D &operator+=(const Vector3D &a);
friend const Vector3D operator+(const Vector3D &a, const Vector3D &b);
};
const Vector3D &Vector3D:
_x += a._x; _y += a._y; _z += a._z; return *this;
}
const Vector3D operator+(const Vector3D &a, const Vector3D &b) {
return Vector3D(a._x + b._x, a._y + b._y, a._z + b._z);
}
void main() {
Vector3D a = Vector3D(1, 2, 3);
Vector3D b = Vector3D(4, 5, 6);
Vector3D c = Vector3D(0, 0, 0);
c += a + b;
}