Assigning a static array

bearophile bearophileHUGS at lycos.com
Thu Apr 18 15:08:48 PDT 2013


Steven Schveighoffer:

> There is no guarantee that the incoming array from a variadic 
> function is heap-based.
>
> But an interesting way to deal with it is that you can overload 
> with an explicit slice parameter, and the variadic version will 
> ONLY bind to a variadic call.
>
> For example, in dcollections' ArrayList I have two constructors:
>
>    /**
>      * Create an array list based on a number of elements.
>      */
>     this(V[] elems...)
>     {
>         _array = elems.dup;
>     }
>
>     /**
>      * Use an array as the backing storage.  This does not 
> duplicate the
>      * array.  Use new ArrayList(storage.dup) to make a 
> distinct copy.  Beware
>      * of using a stack-based array when using this constructor!
>      */
>     this(V[] storage)
>     {
>         _array = storage;
>     }

To avoid those bugs I have suggested the simpler possible thing: 
(V[] elems...) to dup the data on the heap every time. In theory 
if you write "(scope V[] elems...)" it will be free to not dup 
the data, avoiding the heap allocation and the associated little 
performance loss. In practice as you know "scope" is not yet 
implemented. D2 language is not close to being fully implemented.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list