std.collection - changing the collection while iterating

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 22 07:03:01 PDT 2015


On Monday, 22 June 2015 at 06:29:20 UTC, Andrei Alexandrescu 
wrote:
> The matter is very well understood. My point here is that 
> leaving it to the user to make sure which ranges are still 
> valid vs. not is not appropriate for D's container. -- Andrei

If we mean that we don't want undefined behavior, and we want to 
do something like throw Errors when a programmer screws up and 
uses an invalidated range, then fine - especially if it's 
restricted to version(assert) like we've recently been doing with 
our checks for calling popFront or front on empty ranges in 
Phobos - then logic errors with containers can be caught more 
easily. But if you mean that the programmer shouldn't have to 
know what types of operations are going to invalidate a range for 
a specific container type, I don't see how that makes any sense 
at all. How can anyone expect to use a container without 
understanding it well enough to know what's going to happen when 
they start adding elements to it or removing elements from it 
while iterating over it? IIRC, Java tries to be nicer than C++ 
and throws an exception when you screw that up rather than 
treating it as undefined behavior, but even they don't try and 
make it work for you. You need to understand the container types 
that you're using if you expect your code to be correct or 
efficient.

And remember that we're already dealing with undefined behavior 
with all ranges with stuff like what happens when you call front 
or popFront (or pretty much anything other than empty) on an 
empty range. So, it's not like we're not going to have undefined 
behavior involved here. You're just looking to avoid it in an 
additional case where folks have used a range incorrectly. I'd 
suggest that we do with containers what we've taken to doing with 
ranges in Phobos in the last year or so and add checks in 
version(assert) blocks which throw Errors when you screw up 
(which in the case of ranges in general would be throwing in 
functions like front or popFront when the range is empty, and in 
the case of ranges for containers would mean throwing an Error 
when you try and do something with them after they've been 
invalidated).

But I don't think that it's at all unreasonable to consider code 
that tries to iterate over an invalidated range to be a logic 
error that the programmer needs to fix. Programmers should know 
when what they're doing to a container is going to invalidate its 
existing ranges.

- Jonathan M Davis


More information about the Digitalmars-d mailing list