More magical AA semantics

Jens Mueller jens.k.mueller at gmx.de
Fri Jan 11 03:24:15 PST 2013


Don wrote:
> Consider this code:
> ---
>    int[int] x;
> 
>    int k = x[2] + 5; // Error, range violation. Makes sense.
> 
>    x[2] = x[2] + 5;  // But this works!!!
> ---
>
> That is, x[2] doesn't exist, *unless you are about to assign to
> it*.
> What happens is:
> 1. lvalue index (creates x[2], sets it to int.init)
> 2. rvalue index (returns x[2], which is now 0)
> 3. lvalue index assign (sets x[2] = 5)
> 
> In reality, step 1 returns a pointer to the newly created element.
> 
> How could this be implemented as a library type?
> The superficially similar case, x[2] += 5; can be implemented
> with opIndexOpAssign. But I don't know how to do this one.
> 
> Note that elements are not always magically created when an
> lvalue is required. AFAIK it only happens in assignment. For
> example this code gives a runtime error:
> ---
> void foo(ref int g) { ++g; }
> 
>    int[int] x;
>    foo( x[2] );  // range error, x[2] doesn't exist yet
> ---

I don't know how opIndex is defined and I cannot find appropriate
documentation at http://dlang.org/hash-map.html.
But you're right this is odd. Either opIndex throws a RangeError or it
creates a value.
I would probably go with the C++ approach: creating the value if it does
not exist. I.e. making the second statement legal. Then k is int.init +
5.
Sorry for my first post. I didn't see it clear.

Jens


More information about the Digitalmars-d mailing list