Question

In my program, I have a class that I want to be allocated before entering main(). I'd like to tuck these away in a separate module to keep the clutter out of my code; However, as soon as the module goes out of scope (before main() is entered), the objects are deallocated, leaving me trying to use a null reference in main. A short 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 getting used to the concept of modules being the basic unit of encapsulation, as opposed to the class in C++ and Java. Is this possible to do in D, or must I move my initializations to the main module?

Was it helpful?

Solution

Here:

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

"start" is a local scope variable that shadows global one. Global one is not initialized. After I have changed this to:

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

Program crashed no more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top