opOpAssign of AA: defined behavior?

Steven Schveighoffer schveiguy at gmail.com
Tue Jun 23 12:47:02 UTC 2020


On 6/23/20 5:15 AM, WebFreak001 wrote:
> I have the following code:
> 
>      double[string] foo;
>      foo["a"] += 1;
> 
> how is the opOpAssign on the AA defined? Is it defined to set the value 
> to the value to the right of the opOpAssign if it isn't set for 
> primitives or does it add the given value onto T.init?
> 
> Doing
> 
>      foo["b"]++;
> 
> gives me 1, so this looks like it comes from an arbitrary 0, however 
> when I do
> 
>      double v = foo["c"]++;
> 
> I wanted to find out what initial value it is basing the increment off, 
> however on dmd this triggered a segfault and on ldc this gave me 0. 
> Where did the 0 come from? double.init should be NaN

I agree. I don't think it's defined by the language, but by the 
implementation.

Looking at the implementation, it's here: 
https://github.com/dlang/druntime/blob/2cc13ead1e7e535ef8ebd1f600d4ffb508a93f98/src/rt/aaA.d#L502-L577

Note the statement "[Returns:] If key was not in the aa, a mutable 
pointer to newly inserted value which is set to all zeros"

This is specifically where the zeroing happens: 
https://github.com/dlang/druntime/blob/2cc13ead1e7e535ef8ebd1f600d4ffb508a93f98/src/rt/aaA.d#L220

IIUC, this is a direct binding from the language, so we may not have the 
ability to set to init value in object.d, it would have to be done here.

-Steve


More information about the Digitalmars-d-learn mailing list