Bug 20605 – static constructor in template run after usage

Status
NEW
Severity
normal
Priority
P3
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2020-02-24T14:34:08Z
Last change time
2024-12-13T19:07:13Z
Keywords
spec, wrong-code
Assigned to
No Owner
Creator
Steven Schveighoffer
Moved to GitHub: dmd#17940 →

Comments

Comment #0 by schveiguy — 2020-02-24T14:34:08Z
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
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/17940 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB