On 01/31/2017 03:15 PM, bitwise wrote:

> If the object is defined at module scope as shared static immutable

Yes, the situation is different from C++ but it's always possible to call a function (which constructor is one) to make the object.

It is indeed possible to initialize immutable objects by pure functions as done inside shared static this() below:

import core.stdc.stdlib;

struct Foo(T)
{
    T* payload;

    ~this() { free(payload); }

    void foo() {
        // do something with payload that fails if not initialized
    }
}

auto makeFoo(T)() {
    // This could be a static member function, even opCall().

    auto p = cast(T*)malloc(T.sizeof);
    *p = 42;
    return immutable(Foo!T)(cast(immutable(T)*)p);
}

shared static immutable(Foo!int) foo;

shared static this() {
    foo = makeFoo!int();
}

void main() {
    assert(*(foo.payload) == 42);
}

Ali

Reply via email to