Should range foreach be iterating over an implicit copy?

Ken kennethuil at gmail.com
Thu Jun 7 14:24:27 PDT 2012


On Wednesday, 16 May 2012 at 21:40:39 UTC, Andrei Alexandrescu 
wrote:
> On 5/16/12 4:37 PM, Nick Sabalausky wrote:
>> One counter-argument that was raised is that TDPL has an 
>> example on page 381
>> that indicates foreach iterates over an implicit copy. I don't 
>> have a copy
>> handy ATM, so I can't look at it myself, but I'd love to see 
>> Andrei weigh in
>> on this: I'm curious if this example in TDPL made that copy 
>> deliberately, or
>> if the full implications of that copy were just an oversight.
>
> It is deliberate and the intent is that millions of programmers 
> used to foreach from other languages don't scream "where is my 
> range???"
>
> Andrei

According to the docs, however, an InputRange that is not a 
ForwardRange won't necessarily behave the way millions of 
programers used to foreach from other languages expect them to.  
Such an operation will most likely consume the underlying data, 
whether foreach makes an implicit copy or not.

Put another way, whether a non-ForwardRange is consumed by a 
foreach the way it currently works is unspecified.

The docs also say that the right way to checkpoint a ForwardRange 
is by calling save().

This tells me that the most intuitive way for foreach to work is:

a. If it's a ForwardRange, make a copy with save(), then consume 
the copy.
b. If it's not a ForwardRange, consume the original.


More information about the Digitalmars-d mailing list