User defined forward range - foreach initializes f.r.
monarch_dodra via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 13 13:11:38 PDT 2014
On Friday, 13 June 2014 at 19:03:12 UTC, Ali Çehreli wrote:
> 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
Yes.
`fun(T)(T[]...)` is just both `fun(T...)(T t)` and `fun(T)(T[]
t)` both "conveniently" packaged into one, but with twice the
pitfalls.
I'd suggest avoiding it altogether. It's a non-feature (IMO).
More information about the Digitalmars-d-learn
mailing list