order of static constructor execution

Robert Clipsham robert at octarineparrot.com
Fri Mar 12 09:03:51 PST 2010


On 12/03/10 16:44, Robert Clipsham wrote:
> I don't know the full situation, or even if this will help, but maybe
> something like the following could help?
>
> a.d:
> ----
> module a;
> import b;
>
> Foo fooA;
>
> static this()
> {
> fooA = bar();
> }
> ----
> b.d:
> ----
> module b;
> import a;
> class Foo { }
>
> Foo bar()
> {
> return new Foo;
> }
>
> Foo fooB;
>
> pure static this()
> {
> fooB = bar();
> }
> ----
>
> Here the pure notates that the static constructor doesn't not depend on
> any other modules (it's pure at module scope rather than function
> scope). If a module's static ctor is pure it doesn't matter what order
> it is executed in, so can be decided arbitrarily by the compiler. Doing
> this means you can have cyclic dependencies both with static
> constructors, without worrying about cyclic dependencies. It does
> however mean that you wouldn't be able to use functions from module C,
> it's better than the current situation though.

Another possible expansion of this to make it more flexible, but then 
pure might not be the correct keyword to use... The ctor could allow 
dependencies on other modules, as long as the other modules did not have 
cyclic dependencies/only had pure ctor's also. This would allow for 
something more complex like:

a.d:
----
module a;
import b;

Foo fooA;

static this()
{
    fooA = bar();
}
----
b.d:
----
module b;
import a;
import c;
class Foo : C { }

Foo bar()
{
   return new Foo;
}

Foo fooB;

pure static this()
{
    // This depends on module c, but c's does not have cyclic
    // dependencies, and its ctor is pure so it is safe to allow it
    fooB = bar();
}
----
c.d:
----
module c;
class C
{
}

C myC;

pure static this()
{
   myC = new C;
}
----



More information about the Digitalmars-d mailing list