Behavior of opEquals

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Fri Sep 4 23:26:26 PDT 2015


On Friday, 4 September 2015 at 19:25:35 UTC, H. S. Teoh wrote:
> Wait, wait, did I miss something? Since when was operator 
> overloading allowed as free functions? Or is opEquals a special 
> case?

Clearly, you haven't read TDPL recently enough. ;)

There is a free function, opEquals, in object.d which gets called 
for classes, and _it_ is what == gets translated to for classes, 
and it calls the member function version of opEquals on classes:

https://github.com/D-Programming-Language/druntime/blob/master/src/object.d#L143

This allows us to avoid a number of fun bugs with opEquals that 
you get in languages like Java and makes it completely 
unnecessary to do stuff like check whether the argument to 
opEquals is null. Timon gave the link to the explanation in the 
spec:

http://dlang.org/operatoroverloading.html#equals

but TDPL also talks about it. But as part of the fix for

https://issues.dlang.org/show_bug.cgi?id=9769

we need to templatize the free function opEquals so that it 
doesn't require Object. Then opEquals on a class will take 
whatever the most base class in your class hierarchy is that has 
opEquals rather than Object, and we can actually deprecate 
opEquals on Object (though that may require some additional 
compiler help rather than simply deprecating it; I'm not sure). 
Regardless, templatizing the free function version of opEquals is 
the first step towards that.

- Jonathan M Davis


More information about the Digitalmars-d mailing list