
Vector3d operators
Posted Wednesday, 23 June, 2010 - 17:45 by anathema inI notice that the implementation of (eg) Vector3d operator + is:
public static Vector3d operator +(Vector3d left, Vector3d right) { left.X += right.X; left.Y += right.Y; left.Z += right.Z; return left; }
I am curious as to why it was done this way - I would have expected it to read:
public static Vector3d operator +(Vector3d left, Vector3d right) { return new Vector3d(left.X + right.X, left.Y + right.Y, left.Z + right.Z); }
If you write:
Vector3d first = new Vector3d(1, 1, 1); Vector3d second = new Vector3d(2, 2, 2); Vector3d result = first + second;
then I'd expect result to have the value (3, 3, 3) and first and second to remain unchanged. The current implementation is really a += rather than a +.


Comments
Re: Vector3d operators
'left' is passed by value (it's a structure, System.ValueType).
So we are changing our local copy, not the original passed vector.
I'm using vector operations extensively. I'm sure 99% of them are correct.
Re: Vector3d operators
So it is - sorry, didn't notice that! :-(