On 04/26/2014 12:10 PM, spec wrote:

> Hello, i'am experiencing some non consistent behavior with static
> constructors. I wonder if this is some bug or i just don't know enough
> of D (most probably!).. Code example bellow:
>
> //------------------------------------------
> module main;
>
> import std.stdio;
>
> class B
> {
>      static this()
>      {
>          A a = new A;
>          int val = a.getValue("A");
>      }
> }
>
> class A {
>      private static int[string] aa;
>
>      static this()
>      {
>          aa = ["A":1, "B":2];
>          writeln("@ A static ctor!");
>      }
>
>      int getValue(string str)
>      {
>          return aa[str];
>      }
> }
>
>
>
> void main(string[] args)
> {
>      B B = new B;
> }
> //------------------------------------------
>
> The text "@ A static ctor!" never gets printed. The inconsistency (IMHO)
> is that if i do any of this:
> - Declare class A before B;
> - Change the var declared in A from an AA to some other p.e int;
> - Comment the line "int val = a.getValue("A")";
>
> Maybe there are some other points, but at this point i got confused and
> decided trying to understand it. Anyway with any of those changes the
> text gets printed.
>
> Anyone able to shed some light into this?
>
> Cheers,

I don't know whether the inconsistency is a bug but according to documentation, static this inside a module are executed in lexical order: "Static constructors within a module are executed in the lexical order in which they appear."

  http://dlang.org/class.html#StaticConstructor

So, if B depends on A then A's static this must appear before B's.

Ali

Reply via email to