Bug 887 – TypeInfo does not correctly override opCmp, toHash
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D1 (retired)
Platform
x86
OS
All
Creation time
2007-01-25T20:08:00Z
Last change time
2014-02-16T15:23:07Z
Assigned to
bugzilla
Creator
fvbommel
Comments
Comment #0 by fvbommel — 2007-01-25T20:08:18Z
-----
urxae@urxae:~/tmp$ cat ti_comp.d
import std.stdio;
class Foo {}
class Bar {}
void main() {
TypeInfo ti_foo = typeid(Foo);
TypeInfo ti_bar = typeid(Bar);
writefln("typeid(Foo).toHash: ", ti_foo.toHash());
writefln("typeid(Bar).toHash: ", ti_bar.toHash());
writefln("opEquals: ", ti_foo == ti_bar ? "equal" : "not equal");
writefln("opCmp: ", ti_foo.opCmp(ti_bar) == 0 ? "equal" : "not equal");
}
urxae@urxae:~/tmp$ dmd -run ti_comp.d
typeid(Foo).toHash: 522954235
typeid(Bar).toHash: 522954235
opEquals: not equal
opCmp: equal
-----
TypeInfo.opCmp compares only the class, not the instance. This may be correct for basic types such as char, int and long, but it's plain wrong for classes, structs, pointers, and other user-defined or derived types.
opEquals *is* overridden correctly AFAICT. So basically any TypeInfo_* class with an overridden opEquals needs to also override opCmp.
toHash is less serious, since it isn't *required* to be distinct but it has essentially the same issue.
The combined effect of these defects is that TypeInfo is useless as an associative array key type. A workaround is to use char[] keys, and use TypeInfo.toString(). (toString seems to be overridden just fine as well)
A quick fix for both of these problems would be to replace 'this.classinfo.name' in both TypeInfo.opCmp and TypeInfo.toHash with 'this.toString()', though that's probably not the most efficient method.