Should range foreach be iterating over an implicit copy?

Steven Schveighoffer schveiguy at yahoo.com
Thu May 17 08:05:46 PDT 2012


On Wed, 16 May 2012 17:37:14 -0400, Nick Sabalausky  
<SeeWebsiteToContactMe at semitwist.com> wrote:

> A small debate has broken out over on D.learn (
> http://forum.dlang.org/thread/jovicg$jta$1@digitalmars.com#post-jovicg:24jta:241:40digitalmars.com  
> )
> that I thought I should move here.
>
> Basically, the issue is this: Currently, when you have a struct-based  
> range,
> foreach will iterate over a *copy* of it:
>
>     Range r;
>     auto save = r;
>     foreach(e; r)
>         assert(r == save);
>     assert(r == save);
>
> One side of the argument is that this behavior is correct and expected  
> since
> structs are value types, and iterating shouldn't consume the range.
>
> My argument is this:
>
> First of all, foreach is conceptually a flow-control statement, not a
> function. So I'd intuitively expect:
>
>     Range r;
>     foreach(e; r) {...}
>
> To work like this:
>
>     Range r;
>     for(; !r.empty; r.popFront)
>     {
>         auto e = r.front;
>         ...
>     }

Hm... proposal:

foreach(e; ref r)
{
}

equates to your desired code.  Would this help?

-Steve


More information about the Digitalmars-d mailing list