Confused about class equality

bearophile bearophileHUGS at
Tue Apr 6 18:15:02 PDT 2010

Time ago I have told Walter that adding images with pointers and boxes to the D docs, that represent the main data structures used in D, can help a lot the understanding and usage of D.

When you *see* the data structure in an image, understanding what happens and how to write program gets easy. So I'd like to see images of the virtual table, an object, interface, etc.

A class reference is a pointer, that is the index (an integer number) of the first byte of RAM of a segment of RAM.

The segment of ram contains the class instance data, plus two more pointers at its start, one to the virtual table, and one to the monitor. The virtual table is a struct that contains indirect pointers to the virtual functions and more. I don't know the layout of the virtual tables in dmd. And I have no idea how the monitor is structured, it's a mystery for me still. I am learning still.

All the instances of a single class point to the same virtual table. Instances of different classes contain pointers to different virtual tables. All objects in D have a pointer to VPT, even classes with no virtual methods. (Structs have no pointer to monitor and vtbl, but they can have a pointer to outer scope if they are not static. This is true for classes too, and there is a little more complexity coming from template instantiations inside functions in D).

When you instantiate a class you create a new section of memory that contains the class members, plus the two pointers.

You can have more than one reference to the same object. And two distinct objects in memory can have the same data into their members.

The "is" operator just compares the class instances, if they are equal (the optimizer can avoid some tests if it knows the objects are surely different, because it knows the static types).

The == among class instances does several things. See D docs page about operator overloading. But basically it tests if the references are the same. If it's true, then they are two references to the same class instance, so they must be equal, and the == returns true.
If the references are different it tests for equality of all members, and returns true if they are all equal, otherwise false.


More information about the Digitalmars-d-learn mailing list