How to Compare 2 objects of the same class

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 3 16:32:44 PDT 2017


On 06/03/2017 03:38 PM, Mark wrote:

 > Ok. So by using '==' it should compare the addresses of the objects?

That's the default behavior. You can change it with opEquals:

   http://ddili.org/ders/d.en/object.html#ix_object.opEquals

I think you want to use the 'is' operator:

   http://ddili.org/ders/d.en/class.html#ix_class.is,%20operator

It's better because 'is' can be used with null variables.

 > about 45 lines, that might be a lot of code
 > for a post.

Yeah. Minimal is good. :)

 > how Can I obtain the actual memory address of a class?

You mean the memory address of a class object. ;) It's achieved with the 
special semantics of casting the class variable to void*:

class C {
     int i;
}

void info(C o) {
     import std.stdio;
     writefln("  Object at %s,\n" ~
              "i member at %s\n", cast(void*)o, &o.i);
}

void main() {
     auto a = new C();
     auto b = new C();

     a.info();
     b.info();
}

Sample output on my system:

   Object at 7F810AA53060,
i member at 7F810AA53070

   Object at 7F810AA53080,
i member at 7F810AA53090

The difference of 16 bytes are from vtbl pointer and the monitor. (I 
think the latter is a kind of a lizard, which nobody actually uses. :p)

Ali



More information about the Digitalmars-d-learn mailing list