Weird rule for immutable

Timon Gehr timon.gehr at gmx.ch
Sun Apr 12 02:26:13 UTC 2020


On 11.04.20 03:19, Victor Porton wrote:
> https://dlang.org/spec/const3.html has a weird rule:
> 
> "The second way is to cast data to immutable. When doing so, it is up to 
> the programmer to ensure that any mutable references to the same data 
> are not used to modify the data after the cast."
> 
> This rule is weird because it disallows the following code:
> 
> int[] x = [];
> {
>    immutable y = cast(immutable)x;
> }
> x = [1, 2];
> ...

It does not. You are not mutating any data that has been cast to 
immutable, you are just rebinding a mutable reference.

Maybe you meant to write something like this instead:

int[] x = [1, 2];
{
     immutable y = cast(immutable)x;
}
x[0] = 3;

> Here x is modified only after the immutable reference goes out of scope.___
> 
> Why this is disallowed? Is it the language designers' intention? Why? Or 
> is it bad wording in the specification?
> ...

The wording in the spec is (probably) both intentional and bad.

> Consider another example, I assume also invalid(?):
> 
> void f(ref immutable int v) { }
> 
> int x = 1;
> f(cast(*immutable(int*)&x);
> x = 2; // the immutable reference does not exist at this point
>         // but the assignment is disallowed(?)

According to spec I think it's invalid, therefore it is impossible to 
manually manage immutable memory. I think the specification should 
rather be something along the lines that it is undefined behavior to 
read different values using the same (logical) reference to immutable data.


More information about the Digitalmars-d mailing list