Safe to remove AA elements while iterating over it via .byKeyValue?
ikod
igor.khasilev at gmail.com
Mon Sep 28 17:18:41 UTC 2020
On Monday, 28 September 2020 at 14:58:15 UTC, Steven
Schveighoffer wrote:
> On 9/27/20 4:43 PM, Per Nordlöw wrote:
>> On Sunday, 27 September 2020 at 14:23:11 UTC, H. S. Teoh wrote:
>>> No. Modifying a container while iterating over it is, in
>>> general, a bad idea (unless the container is designed to be
> So the major problem of removing keys while iterating is that
> the AA can decide to rehash and shrink. If it does this, your
> iterator is invalidated -- you might skip elements that are
...
>
> How do you "detect" this at compile time?
I think idea was to have some attributes that collection
programmer may attach to implementation, like enums:
SafeToRemoveOnIteration, SafeToAddOnIteration and so on, which
may be checked at compile time when foreach is handled by
compiler. Then in the foreach body compiler can refuse to call
some unsafe methods. I do not know if it is worth of
implementation, just this this was an idea.
>
> One could write a specific function to iterate and remove. I
This looks like dead end to me, as you may not only remove items
from arbitrary positions while iterating over collection, but
also insert items. Also this can happens not only inside foreach
body, but in other kinds of iteration. And also there can be
nested iterations over same collection.
> did it for dcollections (this was actually a very important
> functionality that I missed from C++ std::map, which is why I
> created dcollections in the first place).
>
> I don't think it's worth worrying about this at compile time,
> or even at runtime. Just identify that if you do it, you are
> subject to peculiarities.
Yes, compile-time check is just nice option.
>
> Then, we can introduce a specific mechanism to do this (total
> strawman, have no idea what the best thing looks like):
>
I have an idea on how to implement this, trading up memory for
performance in some rare cases. Just need some time to estimate
how it works.
Igor
More information about the Digitalmars-d-learn
mailing list