How do you initialize a class instance which has static storage within another class?

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 30 14:28:58 PST 2016


On Sat, 30 Jan 2016 22:02:10 +0000, Enjoys Math wrote:

> On Saturday, 30 January 2016 at 21:52:20 UTC, Enjoys Math wrote:
>>
>> class A { static B b; } class B {}
>>
>> doing b = new B() does NOT work.
>>
>> Nor could I create a this() {} at module level
> 
> More info:
> 
> B : A
> 
> so I can't do
> 
> class A {
>    this () {
>      if (b is null) {
>          b = new B();
>      }
> }
> }

You should use a static constructor:

class A {
  static B b;
  static this() { b = new B(); }
}


More information about the Digitalmars-d-learn mailing list