associative arrays

Jonathan M Davis jmdavisProg at
Sun Jan 8 06:06:07 PST 2012

On Sunday, January 08, 2012 14:57:51 simendsjo wrote:
> On 08.01.2012 14:40, Jonathan M Davis wrote:
> > On Sunday, January 08, 2012 14:24:32 simendsjo wrote:
> >> Thanks for your clarifications.
> >> 
> >> Does this mean even this is undefined?
> >> aa["a"] = new C();
> >> auto c = "a" in aa;
> >> aa["b"] = new C();
> >> // Using c here is undefined as an element was added to aa
> > 
> > Yes. Depending on the current implementation of AAs and the state of aa
> > when "b" is added to it, c could still point to exactly what it did
> > before, or aa could have been rehashed, which could move any or all of
> > its elements around, in which case who knows what c points to.
> > 
> > - Jonathan M Davis
> Thanks! You've saved me a couple of future bugs :)

No problem. It's a bit like how an array could be reallocated after you append 
to it, which causes slices to no longer point to that array, except that 
unlike the slice the pointer may not point to valid memory. Given that it's 
managed by the GC, it probably isn't pointing to complete garbage, but it 
could be used for something else now.

In general, if you insert or remove elements from a container, you must be 
very careful about any references to the data within the container - be they 
pointers to elements in the container, or iterators or ranges for the 
container. That's why std.container has the stable functions. They guarantee 
that the container's existing ranges don't get invalidated when they're 
called, whereas the ones that aren't stable make no such guarantees. The 
issues with in are just one of the manifestations of the more general issue.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list