Structs and assiciative arrays

Jarrett Billingsley kb3ctd2 at yahoo.com
Mon Apr 23 07:25:01 PDT 2007


"Simen Haugen" <simen at norstat.no> wrote in message 
news:f0if23$24mj$2 at digitalmars.com...
>I just hunted quite some time for a bug that was because I'm using structs
> as the key for associative arrays.
> It worked without problem for a long time, and now after I added a string 
> to
> the struct the associative array wouldnt work.
>
> I found in the documentation:
> " If the KeyType is a struct type, a default mechanism is used to compute
> the hash and comparisons of it based on the binary data within the struct
> value. A custom mechanism can be used by providing the following functions
> as struct members:"
> uint toHash();
> int opCmp(KeyType* s);
>
> After I implemented these everything worked fine.
>
> I wrote a simple test to check if it was because of the string, but
> everything worked in my testcase. So I'm wondering what actually broke 
> it...

It's because strings are reference types.  Even if you had the same string 
value for both structs, they could be pointing to two different memory 
locations, so when the default struct hashing mechanism computes the hash, 
it doesn't take the string value into account, just the reference; hence, 
two structs with the same string value would hash to different locations. 




More information about the Digitalmars-d-learn mailing list