How do I obtain the default hash of a user-defined struct

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Apr 4 10:11:21 PDT 2014


On Fri, Apr 04, 2014 at 04:48:52PM +0000, dnspies wrote:
> On Thursday, 3 April 2014 at 23:01:27 UTC, Steven Schveighoffer wrote:
> >On Thu, 03 Apr 2014 17:42:16 -0400, bearophile <bearophileHUGS at lycos.com>
> >wrote:
> >
> >
> >>I have filed this big problem four years ago or more.
> >
> >Bug report?
> >
> >-Steve
> 
> This is the closest I could find:
> 
> https://d.puremagic.com/issues/show_bug.cgi?id=11025
> 
> Here's a couple other related bugs:
> 
> https://d.puremagic.com/issues/show_bug.cgi?id=12516
> 
> https://d.puremagic.com/issues/show_bug.cgi?id=10374
> 
> https://d.puremagic.com/issues/show_bug.cgi?id=1926

I just found this related issue:

	import std.stdio;
	
	struct MyKey {
		int a;
		char[] b;
	}
	
	void main() {
		auto key1 = MyKey(1, "abc".dup);
		writefln("key1 hash = %x", typeid(typeof(key1)).getHash(&key1));
	
		char[] sneaky = "def".dup;
		key1.b[] = sneaky[]; // N.B.: change array contents, keep same pointer
	
		writefln("key1 hash = %x", typeid(typeof(key1)).getHash(&key1));
	}

Output:

	key1 hash = 6cba62173367a870
	key1 hash = 6cba62173367a870

This means that the hash of MyKey is computed based on its binary
representation, disregarding the contents of any array (and other
reference) fields. This will certainly break AA's.

I'm almost certain this has already been reported as a bug, but I
vaguely remember someone mentioning a while back that this is supposed
to have been fixed. But I still get the above problem in DMD git HEAD.
:-(


T

-- 
GEEK = Gatherer of Extremely Enlightening Knowledge


More information about the Digitalmars-d-learn mailing list