Bug 14245 – Immutable reference to immutable field in constructor allows breaking type system
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2015-03-04T19:02:24Z
Last change time
2018-05-26T09:03:49Z
Assigned to
No Owner
Creator
Marc Schütz
Comments
Comment #0 by schuetzm — 2015-03-04T19:02:24Z
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.
Comment #1 by schuetzm — 2015-06-06T11:24:15Z
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);
}
Comment #2 by edi33416 — 2017-03-07T08:55:04Z
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.
Comment #3 by razvan.nitu1305 — 2018-04-18T09:27:35Z