Static Constructors

BCS ao at pathlink.com
Fri Oct 3 15:11:35 PDT 2008


Reply to Saaa,

> 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?


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;
data[at] = t;
at++;


//when done adding
data.length = at;

another option would be to use an AA if order isn't relevant.

T[int] data;

void reg(T b)
{
  static int a = 0;
  data[a++] = b;
}




More information about the Digitalmars-d-learn mailing list