看看我正在构建的这个简单的类,作为存储字符串匹配算法结果的基础:
/** 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);
}
}
这就是事情变得奇怪的地方:
auto m1 = new Match(1), m2 = new Match(1);
writeln(m1.toHash());
writeln(m2.toHash());
writeln(m1 == m2);
打印
4464528
4464512
false
我认为没有理由默认情况下不应将这两个对象视为相等。我想我可以写一个自定义
toHash()
和 opEquals()
功能,但这似乎有点矫枉过正。根据 Andrei Alexandrescu 的 book在 D 编程语言(好书!)上,“默认情况下,散列是通过使用对象的按位表示来计算的。”有什么想法吗?
最佳答案
你必须执行 toHash
靠你自己,因为 Object.toHash
取决于地址。如果我没记错的话,它只是一个 return cast(hash_t)cast(void*)this
.
编辑:是的,我没记错:https://github.com/D-Programming-Language/druntime/blob/master/src/object_.d#L88
关于object - 为什么这些对象在 D 中默认不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12098606/