When are associative arrays meant to throw a RangeError?

Daniel Murphy yebblies at nospamgmail.com
Fri Feb 17 19:19:22 PST 2012


It's 3.  It also has the nasty side effect that throwing while evaluating 
the rhs leaves the AA with a default-initialized key.

When AA[key] needs to be an lvalue, it gets translated to something like:
*_aa_get_lvalue(AA, key)
which creates the key if it doesn't exist and returns a reference to it.

"Ben Davis" <entheh at cantab.net> wrote in message 
news:jhn2e7$2urh$1 at digitalmars.com...
>I can't easily see what the rules are. Specifically, I'm finding:
>
> Chunk[][char[4]] chunks;
> //chunks["DATA"] is an array of Chunk objects, where Chunk is a class.
> //I'm using this structure to remember positions of chunks in a file 
> format.
>
> //These both work:
> chunks["AAAA"]~=new Chunk();
> chunks["BBBB"]=chunks["BBBB"]~new Chunk();
>
> //These all throw RangeErrors
> Chunk[] tempVar=chunks["CCCC"]~new Chunk();
> if (chunks["DDDD"].length!=1) throw new Exception("");
> writefln("%s",chunks["EEEE"]);
>
> //This works and formats the null as "[]"
> writefln("%s",cast(Chunk[])null);
>
> So, as far as I can tell, chunks[nonexistentKey] throws a RangeError in 
> most cases, including with ~ in general, but not if the ~ is used for an 
> in-place modification.
>
> My initial expectation would be that every example above would throw a 
> RangeError (except the one that doesn't use 'chunks' at all).
>
> So here are my theories, in the approx order I came up with them:
>
> 1=. It's an optimisation accident, and it's meant to throw.
>
> 1=. It's a nasty bodge specifically to make assoc arrays usable with 
> modify-assign expressions.
>
> 3. It could be a quirk of assignment expression evaluation order. Perhaps 
> the assignment expression FIRST creates an entry in the assoc array using 
> the value type's default value (an empty dynamic array), AND THEN 
> evaluates the RHS, which is able to read the empty array that's just been 
> inserted.
>
> Whatever the case, I couldn't find any documentation on the subject. I 
> looked under associative arrays (obviously), and also under assignment 
> expressions, and also under expression statements just for good measure.
>
> Would appreciate any comments :)
>
> Thanks,
>
> Ben :) 




More information about the Digitalmars-d mailing list