Is removing elements of AA in foreach loop safe?

Paul Backus snarwin at gmail.com
Fri Aug 30 15:00:59 UTC 2019


On Friday, 30 August 2019 at 13:43:54 UTC, XavierAP wrote:
> On Thursday, 29 August 2019 at 10:11:58 UTC, berni wrote:
>> Iterating of some structure and removing elements thereby is 
>> always errorprone and should be avoided. But: In case of AA, 
>> I've got the feeling, that it might be safe:
>>
>>> foreach (k,v;ways)
>>>     if (v.empty)
>>>         ways.remove(k);
>>
>> Do you agree? Or is there a better way to achieve this?
>
> It compiles and it runs without throwing any RangeError... So 
> it appears to be safe. Otherwise it'd be a bug that there's not 
> error.

Whether you actually get an error at runtime depends on the load 
factor of the AA. If it drops below a certain threshold, the AA 
will be resized [1], and its original memory will be freed [2].

[1] 
https://github.com/dlang/druntime/blob/master/src/rt/aaA.d#L631
[2] 
https://github.com/dlang/druntime/blob/master/src/rt/aaA.d#L154


More information about the Digitalmars-d-learn mailing list