The spec allows immutable fields to be initialized in a constructor: http://dlang.org/class.html#field-init Unfortunately, it still allows taking references to them before they are constructed. This allows breaking the type system: struct S { immutable int x; this(int a) { import std.stdio; immutable int* b = &this.x; writeln(*b); // prints 0 this.x = a; writeln(*b); // prints value of a } } Suggestion: Disallow taking immutable references (pointers, `ref`) before a field's initialization. Const references are ok.
Full compilable and runnable example (main() was missing): struct S { immutable int x; this(int a) { import std.stdio; immutable int* b = &this.x; writeln(*b); // prints 0 this.x = a; writeln(*b); // prints value of a } } void main() { S(10); }
Adding another example of this issue. immutable(int)* g; struct X { int a = 10; immutable this(int x) { g = &a; a = 42; } } void main() { auto x = immutable X(); } This is problematic in multithreaded environments since the global variable `g` is shared among threads which rely on it's immutability to provide concurrent, lock free, accesses.
PR : https://github.com/dlang/dmd/pull/8189