static initialization question

BCS ao at pathlink.com
Wed Dec 10 15:07:13 PST 2008


Reply to Jarrett,

> On Wed, Dec 10, 2008 at 5:31 PM, Weed <resume755 at mail.ru> wrote:
> 
>> code:
>> 
>> import std.stdio;
>> 
>> class MyClass
>> {
>> invariant uint a = 0;
>> }
>> void main()
>> {
>> static MyClass c = new MyClass;
>> writeln( c.a );
>> }
> It's not the class member that wants static initialization, it's your
> variable declaration.
> 
> static MyClass c = new MyClass;
> 
> This is illegal because static variables must be initialized with
> compile-time constants.  The simple way around this is:
> 
> static MyClass c; // defaults to null
> c = new MyClass;
> Which separates the declaration from initialization.
> 

As long as you do this in main it works. In other functions (that might get 
called more than once) you will need to do something else.

Ripping the variable out of the function would let you use a static constructor:


 class MyClass
 {
   invariant uint a = 0;
 }

 MyClass c;
 static this() { c = new MyClass; }

 void main()
 {
   writeln( c.a );
 }




More information about the Digitalmars-d-learn mailing list