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 dump 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)

Something stream based as I've seen in std.stream are classes, so they are consumed. I'm probably just rambling...

Reply via email to