Static Constructors

Steven Schveighoffer schveiguy at yahoo.com
Sat Oct 4 11:08:49 PDT 2008


"Saaa" wrote
> Can I do something like this, or should I use the static constructor for 
> this?
> If so, how should I set the first parameter:size ?
>
> Fruits fruit[];

typo, and you are using C-style array syntax (which works, but is 
discouraged).  This should be:

Fruit[] fruit;

Means, 'I declare an array of Fruit called fruit'

>
>
> class Fruit
> {
> this( parameters )
> {
> fruit[].length=fruit[].length+1;
> fruit[$-1]=this;


Don't do the [] operator, I think this may create a temporary array struct, 
and would not affect the global variable at all:

fruit.length = fruit.length + 1;

But instead of this, it's probably better to write:

fruit ~= this;

Which does all that work for you :)

> }
> ..
> void stuff()
> {
> }
> ..
> }
>
> new fruit( .. );
> new fruit( .. );
>
> foreach (Fruit f; fruit)
> {
> f.stuff();
> }

This should work, but be aware that it's not thread safe if you are using 
multiple threads.

-Steve 




More information about the Digitalmars-d-learn mailing list