Thread overview | ||||||
---|---|---|---|---|---|---|
|
January 30, 2016 How do you initialize a class instance which has static storage within another class? | ||||
---|---|---|---|---|
| ||||
class A { static B b; } class B {} doing b = new B() does NOT work. Nor could I create a this() {} at module level |
January 30, 2016 Re: How do you initialize a class instance which has static storage within another class? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | On 30.01.2016 22:52, 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
It works when you make b const/immutable:
class A {static immutable B b = new B;} class B {}
If you want/need b to be mutable, you can use a static constructor (`static this`), either in the class or the module:
class A {static B b; static this() {b = new B;}} class B {}
class A {static B b;} static this() {A.b = new B;} class B {}
You could also set it in `main` or another function that runs before b is used, of course.
|
January 30, 2016 Re: How do you initialize a class instance which has static storage within another class? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | 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();
}
}
}
Since it OVERFLOWS THE STACK!!
|
January 30, 2016 Re: How do you initialize a class instance which has static storage within another class? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | 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(); }
}
|
Copyright © 1999-2021 by the D Language Foundation