User defined forward range - foreach initializes f.r.

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 13 11:32:35 PDT 2014


On Friday, 13 June 2014 at 18:14:10 UTC, Andre wrote:
> Hi,
>
> I have a template class "List" which should provide generic 
> list functionality. In my use case, using a class instead a 
> struct
> is more comfortable.
>
> Following unittest fails, although the forward range
> implements the save method.
>
> unittest
> {
> 	auto intList = new List!int(1,2,3);
> 	assert(intList.length == 3);
> 	foreach(item; intList) {}
> 	assert(intList.length == 3);
> }
>
> ...
>
> I already tried different thinks, like using dup or importing 
> std.array.
> But nothing helps, the unittest fails.
> Why it fails?
>
> Kind regards
> André

To add to what H.S. Teoh said, which is good advice, but doesn't 
quite explain why your unittest failed: Foreach takes a copy of 
your range, and then "consumes it". This may or may not have an 
effect on the original range. If you plan to use your range again 
after a call, you are supposed to *save* it:

unittest
{
	auto intList = new List!int(1,2,3);
	assert(intList.length == 3);
	foreach(item; intList.save) {} //HERE
	assert(intList.length == 3);
}

There.


More information about the Digitalmars-d-learn mailing list