On Fri, Dec 07, 2012 at 04:18:00PM +0100, bearophile wrote:
> >struct Array(T) {
> >     this(T items[]...) {
> >         this._array = items;
> >     }
> 
> 
> For a D design bug, I think those items don't get copied. So be
> careful and test the code well.
[...]

Yeah I ran into this issue before. Calling the above ctor by passing in
implicit array (e.g., like "auto x = Array!int(1,2,3);") passes a
*slice* of the function arguments _on the runtime stack_. Then the
assignment statement above simply copies the slice (*not* the data) to
this._array, which is most probably *not* what you want. Namely, once
the function that calls the ctor goes out of scope, your struct will be
holding a slice of invalid memory. (In fact, it doesn't even have to go
out of scope; if later code in the function uses up more runtime stack
space, it will overwrite the original array and thus invalidate the
slice.)

Workarounds:
- Use items.dup. Problem: if you're passing an actual array to the ctor,
  it's unnecessary and inefficient.

- Use an array literal: auto x = Array!int([1,2,3]);, which I believe
  should allocate the array on the heap, and so you're safe to just copy
  the slice. This defeats the purpose of the "items..." syntax, though.


T

-- 
Chance favours the prepared mind. -- Louis Pasteur

Reply via email to