User defined forward range - foreach initializes f.r.

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 13 12:03:11 PDT 2014


I am making the following comment to have others confirm, as well as 
remind others about a potential problem.

On 06/13/2014 11:14 AM, Andre wrote:

 > unittest
 > {
 >      auto intList = new List!int(1,2,3);

[...]

 > class List(T)
 > {
 >      private T[] items;
 >
 >      this(T[] items...)
 >      {
 >          this.items = items;
 >      }

Unrelated to your question, I think that is a bug because you are 
keeping a reference to a temporary array. The compiler will generate a 
temporary array for 1, 2, and 3 and then that array will disappear.

Am I remembering correctly?

If so, I would recommend against 'T[] items...' but use an explicit slice:

     this(T[] items)

The users will slightly be inconvenienced but the program will be correct.

Or, you can continue with 'T[] items...' and then have to take a copy of 
the argument:

         this.items = items.dup;    // copied

That is obviously slower when the user actually passed in a slice. 
That's why I think it is better to take an explicit slice as a parameter.

Ali



More information about the Digitalmars-d-learn mailing list