Take a look at this simple class I’m building as the base to store the results of string matching algorithms:
/** Match of a single pattern in full to a single text. */
class Match {
uint Tpos;
this(in uint Tpos) { this.Tpos = Tpos; }
override string toString() {
return text("Match: Text@",Tpos);
}
}
Here’s where things get weird:
auto m1 = new Match(1), m2 = new Match(1);
writeln(m1.toHash());
writeln(m2.toHash());
writeln(m1 == m2);
prints
4464528
4464512
false
I see no reason why these two objects should not be considered equal by default. I suppose I could write a custom toHash() and opEquals() function, but that seems like overkill. According to Andrei Alexandrescu’s book on the D programming language (great book!), “By default, the hash is computed by using the bitwise representation of the object.” Any ideas out there?
From the source code (dmd2/src/druntime/src/object_.d):
So the answer is simply that’s the way the code is written – they do an identity check rather than a content check. Why is it this way? I don’t really know, but my guess is it was simple to write originally and works well enough that nobody has bothered to come back to it and change it.
On the newsgroup, there’s been some discussion of removing these functions from Object entirely, so if you want == on your classes, you’ll have to implement something. But the time it takes for newsgroup talk to become action when it comes to things like this is usually pretty long. And they might change their minds.
The best way of using class equality currently and probably in the foreseeable future is to write your own opEquals method in the class.