www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - static this() not executed

reply =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
// a.d
module a;
claas A {
	static myTemplate!A app;

	static this() {
		app = new myTemplate!A;
	}
}

void startup(State s){
	s.app = A.app;
}

// b.d
main(){
	State mainState = new State;

	startup(mainState);
}

The first problem I have is, that I can set a breakpoint on the static 
constructor but it's never executed. Later on startup() is executed but 
A.app is NULL. Why is the static constructor not run? I added a shared 
too, but same problem.

What I want to achieve is, that one instance of A is created on program 
start-up in a way that I can later use it. Or what's the best practice 
to instantiate at least one object of a class at startup?

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster
May 08 2019
parent reply =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
On 2019-05-08 17:37:38 +0000, Robert M. Münch said:

 // a.d
 module a;
 claas A {
 	static myTemplate!A app;
 
 	static this() {
 		app = new myTemplate!A;
 	}
 }
 
 void startup(State s){
 	s.app = A.app;
 }
 
 // b.d
 main(){
 	State mainState = new State;
 
 	startup(mainState);
 }
 
 The first problem I have is, that I can set a breakpoint on the static 
 constructor but it's never executed.
That was because I'm starting the D runtime manually and that call came later. However, A.app is still NULL even after the static constructor run. -- Robert M. Münch http://www.saphirion.com smarter | better | faster
May 08 2019
parent reply =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
On 2019-05-08 17:47:35 +0000, Robert M. Münch said:

 However, A.app is still NULL even after the static constructor run.
Forget that... I used my (quite complex code, not exactly reflected in the example) not correctly... works now. -- Robert M. Münch http://www.saphirion.com smarter | better | faster
May 08 2019
parent Ron Tarrant <rontarrant gmail.com> writes:
On Wednesday, 8 May 2019 at 18:06:35 UTC, Robert M. Münch wrote:

 Forget that... I used my (quite complex code, not exactly 
 reflected in the example) not correctly... works now.
For future reference, it sounds like what you're after is a singleton. There's an example here: https://wiki.dlang.org/Low-Lock_Singleton_Pattern Instantiation is done with get() instead of this().
May 09 2019