www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 20605] New: static constructor in template run after usage

https://issues.dlang.org/show_bug.cgi?id=20605

          Issue ID: 20605
           Summary: static constructor in template run after usage
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: spec, wrong-code
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: schveiguy yahoo.com

In the spec, under static constructors
(https://dlang.org/spec/class.html#static-constructor), it states:

Static constructors within a module are executed in the lexical order in which
they appear. All the static constructors for modules that are directly or
indirectly imported are executed before the static constructors for the
importer.

However, this is not the case if the static constructor is inside a template.
Instead, the first instantiation of the template counts as the order it is
executed:

template T() {
   int* T;
   static this() {
     T = new int;
   }
}

int x;
static this() { // executed first
   x = *T!(); // instantiated static ctor executed second.
} 

This will segfault, even though the lexical order should make it work properly.

The compiler should order the static constructor pieces in lexical order of the
file. This should be enough to be able to properly initialize items.

--
Feb 24 2020