Associative arrays in D and default comparators

Walter Bright newshound at digitalmars.com
Fri Sep 8 15:32:32 PDT 2006


Sean Kelly wrote:
> Walter Bright wrote:
>> Sean Kelly wrote:
>>> Walter Bright wrote:
>>>> How do you do a hash for it if there's no constant data?
>>>
>>> Using address, currently :-p  But that obviously has to change.  What 
>>> might make the most sense from a hash perspective would be something 
>>> like this:
>>>
>>> class C {
>>>     hash_t hash;
>>>     hash_t toHash() {
>>>         if (hash != hash.init)
>>>             return hash;
>>>         hash = cast(hash_t) this;
>>>         return hash;
>>>     }
>>> }
>>
>> That will fail if the object gets moved.
> 
> Not at all.  The hash value is stored the first time it's computed, and 
> it will remain constant for the life of the object.  If the object is 
> later moved and a new object created in its old position then the two 
> objects would simply have the same hash value.  Collisions would still 
> be resolved with opCmp or opEquals depending on AA implementation.  In 
> the worst case however, I'll admit that this could result in long hash 
> chains.

Storing a sequence number, instead of the address, will produce the same 
result and will also work with opEquals and opCmp. The only downside is 
you'll need to sync the counter accesses upon construction, but thread 
stuff is sync'd anyway so I don't think that is a big problem.



More information about the Digitalmars-d-bugs mailing list