struct vs class for small math types?

Bill Baxter wbaxter at
Tue Oct 24 13:40:00 PDT 2006

Seems like struct is the way to go for implementing small math types 
like 3D vectors or quaternions that have POD semantics.

However, for example, with 4 doubles in a quaternion we're talking 32 
bytes for just one of those guys.  Normally in C++ I would write 
operator overloads and such using 'const quat&' as the argument type to 
avoid copying the data on the stack.  Is there a way to do that in D? 
Should I be worried?  General rule of thumb for C++ I got from somewhere 
(a Scott Meyers book?) is, if the data is bigger than a pointer, pass it 
by const reference rather than by value.

The lack of constructors or usable initializers seems another issue for 
structs.  I guess I'm supposed to use static opCall to make something 
that looks like a constructor:

static vector opCall(double x, double y, double z)
    vector ret;
    ret.x = x; ret.y = y; ret.z = z;
    return ret;

and opAdd then looks like
vector opAdd(vector v) { return vector(x+v.x, y+v.y, z+v.z); }

which makes the syntax for opAdd and the rest not so bad, but makes me 
more worried about extra temporaries created in an expression like 
vector c = a + b.

(Also it took me a while to realize I could use static opCall for this 
purpose.  I don't think it as obvious as would be using the same 
constructor syntax as classes -- which is what I tried first).


More information about the Digitalmars-d-learn mailing list