Resizing array of classes

Marco Leise Marco.Leise at gmx.de
Fri Oct 19 02:42:04 PDT 2012


Am Fri, 19 Oct 2012 11:09:42 +0200
schrieb "m0rph" <m0rph.mailbox at gmail.com>:

> Suppose I have a dynamic array of classes, something like:
> 
> class Foo {
>      int value;
> }
> 
> Foo[] a;
> 
> Now I want to resize it and initialize new items with default 
> values, so I do following:
> 
> a.length = 10;
> a[0].value = 1;
> 
> And by executing the last line of code I've got a segmentation 
> fault. Apparently a.length = 10 resizes array and creates 10 
> references to Foo, but objects of Foo were not created. Do I need 
> to manually iterate over new items of the array and explicitly 
> call a[i] = new Foo, or there is a better (automatic) way?

When you extend the length of an array, it is filled with
the static .init value for the type, which is null here. I
think you'll have to create the objects manually.

foreach (ref foo; a) foo = new Foo;

-- 
Marco



More information about the Digitalmars-d-learn mailing list