Dynamic array void initialization

Steven Schveighoffer schveiguy at yahoo.com
Tue Mar 8 14:03:00 PST 2011


On Tue, 08 Mar 2011 16:53:08 -0500, Ali Çehreli <acehreli at yahoo.com> wrote:

> On 03/08/2011 01:34 PM, Tom wrote:
>> import std.stdio;
>>
>> struct S {
>> int i;
>> int j;
>> }
>>
>> int main(string[] args) {
>> S[] ss = void;
>> ss.length = 5;
>> foreach (ref s; ss)
>> s = S(1, 2);
>> return 0;
>> }
>>
>> Is the above code correct? (it doesn't work... it blows away or just
>> give and access violation error).
>>
>> I need to create a dynamic array of some struct, but don't want defer
>> contained elements initialization (for performance reasons).
>>
>> Tom;
>
> There is std.array.reserve:
>
> import std.array;
>
> struct S {
>      int i;
>      int j;
> }
>
> int main(string[] args) {
>      S[] ss;
>      reserve(ss, 5);
>
>      // or if you want to confuse yourself (and me):
>      ss.reserve(5);  // same thing as above
>
>      foreach (ref s; ss)
>          s = S(1, 2);
>
>      return 0;
> }

Some clarifications:

it's not std.array.reserve, it's object.reserve, always present, no need  
to import.

I believe if the type contains pointers the GC still writes 0s to the  
unused data to prevent false pointers. However, reserve on an int or a  
struct that just contains ints should not pre-initialize.

reserve ensures appropriate space for appending, it does *not* alter the  
array's length.  So your foreach loop would not execute (at that point,  
ss.length is still 0).

To work properly, you would need to use the append operator.

Bearophile has requested an ability to create a dynamic array  
uninitialized, and I think there is a bug report for that.  Currently,  
there is no "easy way" to do it.

-Steve


More information about the Digitalmars-d-learn mailing list