Static initialization and use of a class in a separate module in D

In my program, I have a class that I want to highlight before entering main (). I would like to remove them in a separate module to clutter up the mess from my code; However, as soon as the module goes out of scope (before main () is entered), the objects are freed, as a result of which I try to use a null reference in the main. A brief example:

// main.d import SceneData; int main(string[] argv) { start.onSceneEnter(); readln(); return 0; } // SceneData.d import Scene; public { Scene start; } static this() { Scene start = new Scene("start", "test", "test"; } // Scene.d import std.stdio; class Scene { public { this(string name) { this.name = name; } this(string name, string descriptionOnEnter, string descriptionOnConnect) { this.name = name; this.descriptionOnEnter = descriptionOnEnter; this.descriptionOnConnect = descriptionOnConnect; } void onSceneEnter() { writeln(name); writeln(descriptionOnEnter); } } private { string name; string descriptionOnEnter; string descriptionOnConnect; } } 

I'm still used to the concept of modules, which are the basic unit of encapsulation, unlike a class in C ++ and Java. Is it possible to do this in D, or should I transfer my initializations to the main module?

+4
source share
1 answer

Here:

 static this() { Scene start = new Scene("start", "test", "test"); } 

"start" is a local region variable that obscures the global one. Global is not initialized. After I changed this to:

 static this() { start = new Scene("start", "test", "test"); } 

The program no longer crashed.

+4
source

Source: https://habr.com/ru/post/1392990/


All Articles