[Issue 19928] disallow modification of immutable in constructor after calling base ctor

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jun 4 10:12:24 UTC 2019


https://issues.dlang.org/show_bug.cgi?id=19928

RazvanN <razvan.nitu1305 at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |razvan.nitu1305 at gmail.com

--- Comment #1 from RazvanN <razvan.nitu1305 at gmail.com> ---
I don't think this issue is valid. If we disallow modification of immutable
fields after a base class ctor is called then it will be impossible to
initialize that field after a super call, which in my opinion is unacceptable
behavior. What happens here is that foo is called before the field is actually
initialized so it reads the default value of x, then it is called again after x
has been initialized. This behavior is correct. The code in the original post
is similar to this:

=============================
import std.stdio : writeln;

struct A
{
    immutable int x;
    this(int)
    {
        foo();
        x = 8;
        foo();
    }

    void foo()
    {   
        writeln(x);
    }       
}

void main()
{
    A a = A(2);
}
=============================

This code compiles and runs successfully. I don't see why it wouldn't. An
alternative approach would be to consider that the first use of x locks down
the variable and future accesses to it are considered modifications, but this
leads to other problems: the constructor will not be able to initialize x and
it would require inter-function compilation to determine this; dmd does not
support inter-function compilation.

I suggest we close this as invalid.

--


More information about the Digitalmars-d-bugs mailing list