[Issue 5207] Immutability is broken in constructors

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Mar 21 09:40:04 UTC 2021


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

--- Comment #6 from RazvanN <razvan.nitu1305 at gmail.com> ---
(In reply to hsteoh from comment #5)
> Are you sure?  I think the complaint here is that `i` should only be
> initializable once in the ctor, and should not be readable until then.
> Otherwise, while inside the ctor immutability is violated, and strange
> things can happen (e.g., the ctor can call a function that receives an
> immutable value, then mutate it afterwards, causing an inconsistent state).
> 

I don't see how this could happen. The value is immutable and therefore it
cannot be changed by anyone else other than the constructor. And that is true
only for the first assignment. In the reported example how is it possible to
change i from a different function?

> The fact that the ctor can initialize the immutable is not the complaint
> here.

I understand what the enhancement request asks for, however, this cannot be
enforced. Imagine this case:

struct A
{
    immutable int i;
    this(int k)
    {
        doSomething();
        i = k;
    }

    void doSomething()
    {
        int a = i;
    }
}

To reject this case the compiler should look at doSomething's body and do some
complicated dataflow analysis. And for what gain? It is fine to read
un-initialized variables because they have a default value. What advantage
would we gain if we forbid that? I think that this enhancement request does
actually bring any benefit, it just complicates the dataflow analysis for no
gain.

--


More information about the Digitalmars-d-bugs mailing list