writing efficient struct operators
blevin
brett.levin at gmail.com
Sun Nov 4 12:49:37 PST 2007
I noticed that dmd generates implicit checks for a NULL "this" argument
in overloaded struct operators. Assuming my operator does not modify
its arguments, including "this", is there a way to avoid that cost?
Putting the equivalent code in a static member function with "in"
arguments avoids the cost but gives up the nice syntax. The struct in
question is a vector, so it'd be nice to provide operators.
Perhaps D2.0's invariant keyword address this? (There doesn't seem to
be a released D2.0 compiler for linux yet, so I haven't checked.)
struct Vec3d
{
double x=0, y=0, z=0;
Vec3d opAdd(Vec3d rhs) {
// Note: implicit assert(this != NULL) inserted here.
// Would marking this method 'invariant' help?
return Vec3d(x+rhs.x, y+rhs.y, z+rhs.z);
}
static Vec3d Add(in Vec3d a, in Vec3d b) {
// Static method avoids the assert
return Vec3d(a.x+b.x, a.y+b.y, a.z+b.z);
}
static Vec3d opCall(double x, double y, double z) {
Vec3d v;
v.x = x;
v.y = y;
v.z = z;
return v;
}
}
thanks,
--
Brett.
More information about the Digitalmars-d-learn
mailing list