Comment #0 by bearophile_hugs — 2014-04-27T22:04:48Z
This was inspired by a problem found by "spec" in D.learn:
http://forum.dlang.org/thread/[email protected]
This reduced program:
struct Foo {
static this() {
Bar b;
int x = b.data[0]; // RangeError
}
}
struct Bar {
static int[] data;
static this() {
data.length++;
}
}
void main() {}
Gives with DMD 2.066alpha:
core.exception.RangeError@test(4): Range violation
If you swap the position of the Foo and Bar classes in the module you receive no errors.
As explained here: >Static constructors within a module are executed in the lexical order in which they appear.<
http://dlang.org/class.html#StaticConstructor
So, if Foo depends on Bar then Bar static this must appear before Foo one.
A similar example:
struct Foo {
static this() {
Bar b;
int x = b.data[0];
}
}
struct Bar {
immutable static int[] data;
static this() {
data.length++;
}
}
void main() {}
So I suggest to introduce a little D breaking change (that probably is not going to break a lot of code. In the shown case it just turns a run-time error in a compile-time one): is it possible and a good idea to raise a compilation error in such cases where code tries to use Bar static fields before bar static this() has run? (Perhaps a more fine-grained error is useful, that tracks single fields, to allow more flexible code of mutually initializing constructors, or perhaps it's not necessary).
Comment #1 by robert.schadek — 2024-12-13T18:20:13Z