D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 14245 - Immutable reference to immutable field in constructor allows breaking type system
Summary: Immutable reference to immutable field in constructor allows breaking type sy...
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86_64 Linux
: P1 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2015-03-04 19:02 UTC by Marc Schütz
Modified: 2018-05-26 09:03 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Marc Schütz 2015-03-04 19:02:24 UTC
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 Marc Schütz 2015-06-06 11:24:15 UTC
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 Eduard Staniloiu 2017-03-07 08:55:04 UTC
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 RazvanN 2018-04-18 09:27:35 UTC
PR : https://github.com/dlang/dmd/pull/8189