[Issue 20605] New: static constructor in template run after usage

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Feb 24 14:34:08 UTC 2020


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 at puremagic.com
          Reporter: schveiguy at 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.

--


More information about the Digitalmars-d-bugs mailing list