AA invalidating pointers and references..?

bearophile bearophileHUGS at lycos.com
Sun Aug 8 15:11:13 PDT 2010


simendsjo:

> I haven't worked much with AA's, but I find the "key in aa returns a 
> reference to the value" to be handy. I think it's better than the following:
> 
> int value;
> if( 1 in a )
>    value = a[1];
> 
> or a[1] in a try/catch or other implementations.

Your examples have shown me that probably the current design can't be made safe, and you can't use in SafeD code.
But performing "x in AA" is a very useful operation that I want to perform in SafeD code.

And in my opinion this code:

int value;
auto ptr = 1 in a;
if (ptr)
    value = *ptr;


Doesn't look better than:

int value;
if (1 in a)
    value = a[1];


> 2) I don't know what you mean. Does a single lookup often involve 
> several under the hood?

If your compiler is naive then code like this:
if (1 in a)
    value = a[1];
requires to perform two searches inside the hash, the first to tell if the key is present, and the second to find it again and fetch its value.

A bit better compiler (LDC is already able to do this) can recognize that you are performing two nearby key searches with the same key, and it can remove the second one, essentially replacing that code with this one:

int value;
auto ptr = 1 in a;
if (ptr)
    value = *ptr;

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list