Static Constructors
Saaa
empty at needmail.com
Sat Oct 4 05:30:11 PDT 2008
>> I've been using classes for a few months now and I keep on making
>> arrays of instances like:
>>
>> class Fruit
>> {
>> this( parameters )
>> {
>> }
>> ..
>> }
>> Fruits fruit[];
>>
>> void init()
>> {
>> fruit.length=fruit.length+1; // annoys me :)
>> fruit[$]=new Fruit( .. );
>> }
>> deleting is even more annoying.
>>
>> Now I've been reading about static constructors and is that somehow a
>> solution to this manual array management?
>>
>
> Sort of: switch "void init" for "static this" and you won't need to call
> init from main, but that's about all you will get. Also you can not
> control the order of execution.
>
> 2 minor nits:
>
>> fruit[$]=new Fruit( .. );
> should be
>> fruit[$-1]=new Fruit( .. );
>
> typo?
yeah :), originally I did fruit[].length-1.
>
> If you are going to be adding more than very few items to the array, pick
> a better allocation scheme
>
> uint at = 0;
>
> if(extra <= at) data.length = (at+1)*2;
extra=data.length; ?
> data[at] = t;
> at++;
>
>
> //when done adding
> data.length = at;
Initially I'd be adding a lot, but after that only sparsely.
>
> another option would be to use an AA if order isn't relevant.
>
> T[int] data;
Is this code? I mean should there be an int or 'int'?
>
> void reg(T b)
> {
> static int a = 0;
> data[a++] = b;
How does this work when it's no dynamic array?
> }
More information about the Digitalmars-d-learn
mailing list