foreach ref very broken: fails to call front(val)

Jonathan M Davis jmdavisProg at gmx.com
Tue Jul 10 14:51:27 PDT 2012


On Tuesday, July 10, 2012 23:25:41 monarch_dodra wrote:
> On Tuesday, 10 July 2012 at 14:19:04 UTC, Andrei Alexandrescu
> 
> wrote:
> > ...
> > 
> > Second, the return by value from Array is intentional and has
> > to do with sealing. Array is intended to never escape the
> > addresses of its elements. That way, the collection is "sealed"
> > in the sense there can never be uncontrolled pointers to its
> > elements. This allows using efficient allocation strategies for
> > the array without compromising its safety.
> > 
> > ...
> > 
> > Andrei
> 
> Thanks for the reply. I had actually opened a thread about making
> Array return by ref, and you answered you thought it was a good
> point, and said that there should be an enhancement request about
> it:
> http://forum.dlang.org/thread/bkozswmsgeibarowfwvq@forum.dlang.org#post-jss5
> iu:24qct:241:40digitalmars.com But I guess you meant for ranges in general.
> I wasn't there for
> the discussions about sealed classes, so I had not considered it.
> 
> ...
> 
> Anyways, still curious about that "foreach with ref" loop: Any
> chance I can expect it to work with Array in a near future? Or if
> not, shouldn't I get a compile error that you can't bind a
> reference to a temporary?
> 
> And more generally, how would code like this _ever_ work?
> 
> Array!int arr
> foreach(ref a; arr)
> a += 5;
> 
> Since there is no mechanism to pass the "op" to "front"?

I believe that according to TDPL, if you use ref in a foreach with a range, 
and range.front = value isn't legal, then you should get a compilation error. 
Whether a += value works depends on whether range.front += value works, and at 
present, that's pretty much only going to work with ranges whose front returns 
by ref, since property syntax isn't currently sophisticated enough to combine 
the getter and setter properties to make stuff like front++ or front += 5 
possible.

- Jonathan M Davis


More information about the Digitalmars-d mailing list