On Wednesday, 16 May 2012 at 21:37:54 UTC, Nick Sabalausky wrote:
A small debate has broken out over on D.learn (
http://forum.dlang.org/thread/[email protected]#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:

http://forum.dlang.org/post/[email protected]

I've replied in the other one, but I'll repost it here, perhaps andrei can correct me.

---

On Wednesday, 16 May 2012 at 20:50:55 UTC, Nick Sabalausky wrote:

I was initially open to the idea I may have just misunderstood something, but I'm becoming more and more convinced that the current "foreach over an implicit copy" behavior is indeed a bad idea.

I'd love to see Andrei weigh in on this. I'm curious if the example you pointed out in TDPL made the copy deliberately, or if the effects of that copy were just an oversight.

I remember going over hard and long over that section. I think it's deliberate.

Range can refer to many things, and I'm assuming array is one of them. So... If the array is consumed when using foreach, that seems dumb right? (An array in the end is just a small struct afterall...)

---
int[] x = [1,2,3];
foreach(i; x) {
 //stuff
}

 assert(x.length == 0, "Should have been consumed!");
---

Structs being value types are by value and so are copied, not referenced. Although referencing a copy does seem a bit silly...

int[] x = [1,2,3];
foreach(ref i; x) {
 i = 10;
}

assert(x == [10,10,10], "But i changed them to 10!!");

--

That means that foreach(ref; ref) if it's considered (And I think it makes sense to) would work for structs in these few cases. (Course you'd still consume dynamic arrays that way)

In std.stream are classes, so they are consumed. I'm probably just rambling...

Reply via email to