how to avoid "cycle detected"?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 1 04:59:58 PDT 2015


On Wednesday, July 01, 2015 09:09:52 aki via Digitalmars-d-learn 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 at src\rt\minfo.d(162): Aborting: Cycle detected
> between modules w
> ith ctors/dtors:
> a -> b -> a

Modules which have static constructors (or destructors) cannot import each
other, because the runtime has no way of knowing which order they should be
run in or even if they _can_ be run in an order that guarantees that you
don't use any variables before they're initialized. So, you either need to
fix it so that your modules with static constructors aren't importing each
(even indirectly), or you need to stop using static constructors in at least
one of them.

The result of this seems to often be that you should avoid static
constructors where reasonably possible, but if your modules are independent
enough, they should be fine. They _do_ need to be fairly independent of each
other though, or you'll probably run into a problem with static constructors
and cyclical imports eventually.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list