Can pointers to values inside associative arrays become invalid?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 6 08:27:58 PST 2015


On Tue, Jan 06, 2015 at 04:18:17PM +0000, Idan Arye via Digitalmars-d-learn wrote:
> I have an associative array, and I use the `in` operator to get a
> reference to a value inside it and store it in a pointer:
> 
>     int[string] aa;
>     aa["myKey"] = 42;
>     int* myPointer = "myKey" in aa;
> 
> Is it possible that due to rehashing or something D will decide to
> move the associative array's values around, resulting in `myPointer`
> no longer pointing to `aa["myKey"]`?

AFAIK, not in the current implementation. Each key/value pair is kept in
its own bucket, and rehashing doesn't move the bucket's position in
memory, only relinks it with the other hash structures.

However, if you delete the key from the AA, you might have problems, as
the current implementation will forcefully call GC.free() on the bucket,
which makes any other pointers to it dangling.

This is all implementation-dependent behaviour, though. If you need to
rely on retaining pointers to keys/values, probably the better thing to
do is to make your keys/values reference types, and keep the references
to them instead of holding on to the pointer returned by 'in'. Relying
on implementation-dependent behaviour is liable to come back to haunt
you later when the implementation changes.


T

-- 
Latin's a dead language, as dead as can be; it killed off all the Romans, and now it's killing me! -- Schoolboy


More information about the Digitalmars-d-learn mailing list