On 7/1/15 5:09 AM, aki wrote:
Following code causes run-time error.
How can I use static this() without causing error?
It's difficult to avoid this situation because
actual code is more complex.

file main.d:
void main() {
}

file a.d:
import b;
class A {
     static this() {}
};

file b.d:
import a;
class B {
     static this() {}
};

object.Exception@src\rt\minfo.d(162): Aborting: Cycle detected between
modules with ctors/dtors:
a -> b -> a

You need to either factor out the static constructors to put them in a leaf module, replace one of them with intializers, or remove one of them.

It can be an exercise in ugly coding, but you can fix this.

I know it wasn't specifically asked, but the reason it exists is simple:

class A {
    static int x;
    static this() { x = B.x + 5;}
}

...

class B {
    static int x;
    static this() { x = A.x + 5;}
}

The runtime cannot introspect the code to detect the circular dependency, so it makes a conservative decision. I'm waiting on an introduction of RTInfo for modules [1] to allow us to mark static ctors as standalone, then we can probably fix this problem through a sort of "trust the programmer" mechanism.

-Steve

[1] https://issues.dlang.org/show_bug.cgi?id=10023

Reply via email to