Can pointers to values inside associative arrays become invalid?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 6 10:26:02 PST 2015


On 1/6/15 12:39 PM, Idan Arye wrote:
> On Tuesday, 6 January 2015 at 16:30:14 UTC, H. S. Teoh via
> Digitalmars-d-learn wrote:
>> 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
>
> I see... quite a shame there are no built-in data structures that
> provide forever-valid references to their members. Arrays can be
> reallocated, associative arrays can be rehased, and the stuff in
> std.collection does not expose the internal references...

Well, the AA will not move your value to another memory location unless 
you remove it. Even with a rehash. But this is NOT guaranteed, future 
implementations may be less friendly to it.

In general, I would consider the value location to remain stable unless 
you modify the container in any way besides changing a value.

-Steve


More information about the Digitalmars-d-learn mailing list