Expected or Bug? struct range unmodified after foreach
Jonathan M Davis
jmdavisProg at gmx.com
Sun Nov 6 16:18:41 PST 2011
On Sunday, November 06, 2011 23:26:02 Jesse Phillips wrote:
> I'm sure if this was changed there would be other interesting behavior,
> such as arrays being consumed. And suggestions other than
>
> for(S s; !s.empty, s.popFront())...
>
> Example:
>
> void main() {
> S s;
>
> foreach(i; s) {
> assert(i == s.popCount); // Fail
> }
>
> assert(s.popCount == 10); // Fail
> }
>
> struct S {
> size_t popCount;
>
> auto empty() {
> if(popCount > 9)
> return true;
> return false;
> }
> auto front() { return popCount; }
> auto popFront() {
> popCount++;
> }
> }
I'd say that it's expected. Stuff isn't normally consumed by foreach iterating
over it - an exception would be a class which is a range, but since it's a
reference, copying it is a shallow copy, unlike with a struct, and my guess
would be that s is being copied when it's passed to the foreach. If it
_wasn't_ copied like this, then passing a range to foreach would consume it
unless you explicitly sliced it or saved it, which would probably break a lot
of code.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list