Can anyone shed any light on why this code doesn't run as expected?
struct vector3D
{
double x, y, z;
vector3D() { }
vector3D(double inX, double inY, double inZ) { x = inX; y = inY;
z=inZ; }
vector3D& operator += (const vector3D &n) { x += n.x; y += n.y; z
+= n.z; return *this; }
vector3D& operator + (const vector3D &n) const { return vector3D
(*this) += n; }
vector3D& operator *= (double n) { x *= n; y *= n; z *= n; return
*this; }
vector3D& operator * (double n) const { return vector3D(*this) *=
n; }
vector3D operator = (const vector3D &n) { x = n.x; y = n.y; z =
n.z; return *this; }
void Print(void) const { printf("(%lg, %lg, %lg)", x, y, z); }
};
void do_test(void)
{
vector3D rayPos(0, 1, 1), rayDir(1, 0, 0);
double propagationDistance = 10.5;
vector3D newRayPos;
newRayPos = rayPos + rayDir * propagationDistance;
newRayPos.Print();
vector3D temp = rayDir * propagationDistance;
newRayPos = rayPos + temp;
newRayPos.Print();
}
When I run it (with all optimizations off) I see the following output:
(0, 2, 2)
(10.5, 1, 1)
I would expect both lines to be identical.
The problem seems to be connected to the use of the "vector3D&"
return type for the various operators. If I remove the "&" the
program works as expected. Note that if I add an "&" to the return
type for "operator=" then neither line of output contains the
correct result.
Am I doing something illegal here or is the compiler generating bad
code? I'd like to be able to understand this because the code runs
much slower if I pass vector3D structures around on the stack...