Resizing array of classes

monarch_dodra monarchdodra at gmail.com
Fri Oct 19 06:46:34 PDT 2012


On Friday, 19 October 2012 at 13:41:53 UTC, Jacob Carlborg wrote:
> On 2012-10-19 11:42, Marco Leise wrote:
>
>> 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;
>
> Is this possible:
>
> a[] = new Foo;
>
> ?

Technically, it will compile and work, but you need to understand 
what it is actually going to do:

It will allocate a single new Foo, and then assign that class 
reference to each and every index in your array. They will 
effectively all point to the same instance, rather than each to 
their own.


More information about the Digitalmars-d-learn mailing list