DMD Bug or not? foreach over struct range

Jonathan M Davis jmdavisProg at gmx.com
Wed May 16 00:03:48 PDT 2012


On Wednesday, May 16, 2012 02:43:19 Nick Sabalausky wrote:
> This code:
> 
> ------------------------------------------
> import std.stdio;
> 
> struct Foo
> {
>     int val;
> 
>     @property bool empty() {
>         return val >= 5;
>     }
> 
>     @property int front() {
>         return val;
>     }
> 
>     void popFront() {
>         val++;
>     }
> }
> 
> void main()
> {
>     Foo foo;
>     foreach(val; foo)
>         writeln(foo.val, " ", val);
> }
> 
> ------------------------------------------
> 
> Expected output:
> 0 0
> 1 1
> 2 2
> 3 3
> 4 4
> 
> Actual output:
> 0 0
> 0 1
> 0 2
> 0 3
> 0 4
> 
> It seems that foreach is iterating over an implicit copy of 'foo' instead of
> 'foo' itself. Is this correct behavior, or a DMD bug?

No. That's expected. Your range is a value type, so it got copied when you 
used it with foreach. Otherwise, if you did

Foo foo
foreach(val; foo)
{}
assert(foo.empty);

that assertion would pass, but it doesn't, and it shouldn't. If your range was 
a reference type (e.g. if it were a class or it was like the ranges in 
std.stdio which deal with I/O), then using it with foreach would consume it, 
but that won't happen with a value type range.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list