objects as AA keys

captaindet 2krnk at gmx.net
Mon Oct 14 22:44:22 PDT 2013


hi,

i am a bit confused.

the official language ref  ( http://dlang.org/hash-map.html ) states:
"
Classes can be used as the KeyType. For this to work, the class definition must override the following member functions of class Object:
hash_t toHash()
bool opEquals(Object)
int opCmp(Object)
...
"

but now i stumbled on http://forum.dlang.org/post/mailman.2445.1354457588.5162.digitalmars-d-learn@puremagic.com
"
int[typeof(O)] rc;
rc[O] = 42;
auto O2 = O;
// [...]
if (auto r = O2 in rc)
    return *r;
else
    return rc[O2] = compute(O2);

IOW explicitly taking the address may not be necessary when doing that kind of things.
"

and i did a quick test and indeed, it seems to work out of the box - without overriding any member functions. in my use case, i wouldn't be able to modify the class anyway.

so my questions:

why is it working, is it just syntactic sugar for using cast(void*)Obj as key?

what is the danger of using objects as keys? when would it fail?

as it seems to be working against language specs, will this 'feature' eventually be removed?
(then maybe i should use cast(void*)Obj right away...)


thanks, det



More information about the Digitalmars-d-learn mailing list