static initialization question

Denis Koroskin 2korden at gmail.com
Wed Dec 10 15:28:26 PST 2008


On Thu, 11 Dec 2008 02:13:58 +0300, Weed <resume755 at mail.ru> wrote:

> Denis Koroskin пишет:
>> On Thu, 11 Dec 2008 01:31:32 +0300, Weed <resume755 at mail.ru> wrote:
>>
>>> But my class does not contain data that need initialization and can be  
>>> created
>>> in compile time
>>>
>>> code:
>>>
>>> import std.stdio;
>>>
>>> class MyClass
>>> {
>>>     invariant uint a = 0;
>>> }
>>>
>>> void main()
>>> {
>>>     static MyClass c = new MyClass;
>>>     writeln( c.a );
>>> }
>>  There is a memory allocation that may occurs at run time only.
>
> In C++ analogous construction means creation of uninitialized static  
> pointer (in compile time) and it's initialization at first execution  
> this line in the function.
>
> Why D does not behave that way on this construction?

You can this easily yourself.

// That's what C++ do under the hood:
static MyClass c = null;
if (c is null) {
    c = new MyClass();
}

But it is
a) thread-unsafe
b) a runtime check is done upon every function execution

It can be replaced with a more sophisticated (and error prone) solution:

static MyClass c = null;
if ( (auto old = c) is null ) {
    MyClass tmp = new MyClass();
    if (!CAS(&c, old, tmp)) {
        delete tmp;
    }
}

While it is (arguably) safe, two object might co-exist for a short amount of time, which is unacceptable in many case.

As a summary, the C++ solution is full of problems and leads to bad design practices. The D way is to avoid them.

You should use a private global variable that is initialized in a static initializer (static this) or a plain old struct, instead.


More information about the Digitalmars-d-learn mailing list