Weird opEquals Problem
Jonathan M Davis
jmdavisProg at gmx.com
Wed Feb 22 18:08:24 PST 2012
On Wednesday, February 22, 2012 20:51:50 Kevin wrote:
> I have the following code which gives the same result on ldc2 and dmd.
> If I compare two objects of different classes I always get false even
> though the comparator is called.
> The key thing to notice is that opEquals() gets called both times. Any
> ideas about what is happening?
That's easy. It's because opEquals must be true in both directions, and it's
not. a == b does _not_ do a.opEquals(b) in D. It does opEquals(a, b), where
opEquals is a free function. And Object's opEquals does not consider the two
to be equal.
I don't remember _exactly_ how the free function version of opEquals lined out
(I believe that TDPL explains it), but it's something like
bool opEquals(Object a, Object b)
{
if(a is b)
return true;
if(a is null || b is null)
return false;
return a.opEquals(b) && b.opEquals(a);
}
This helps some of the problems you get with opEquals in other languages such
as Java. It also checks for null, so you don't have to worry about a null
object causing a segfault.
If you added an opEquals to B which printed, you'd see it print as well. If
you make it return false, you'll get the same behavior as now, and if you make
it return true, then your program will work.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list