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.
Comment #1 by bugzilla — 2020-11-08T07:15:27Z
A better solution is to clarify in the spec what happens with templated initializations, and this approach also won't risk breaking code.
Comment #2 by robert.schadek — 2024-12-13T19:07:13Z