Store mutable indirections in immutable data with this one weird trick!

tsbockman thomas.bockman at gmail.com
Sat Nov 13 08:30:58 UTC 2021


On Saturday, 13 November 2021 at 07:20:37 UTC, Timon Gehr wrote:
> It does not matter how you do it if the compiler assumes it 
> does not happen...
>
> DMD 2.098.0:
>
> ```d
> void main()@safe{
>     immutable TailUnqual!(int*) p = new int(123);
>     auto mut = p.ptr;
>     immutable immut = p.ptr;
>     import std.stdio;
>     writeln(*immut); // 123
>     *mut=0;
>     assert(mut is immut);
>     assert(*mut == *immut);
>     writeln(*mut," ",*immut); // 0 123
> }
> ```

That's a compiler bug. The explicit return type of `ptr` is being 
ignored when assigning to `immutable immut`. Stupid fix:

```D

     private __gshared int dummy = int.min;

     @trusted @property
     P ptr() inout
     {
         P ret = & dummy; // Persuade the frontend to actually use 
the explicit return type.
         ret = cast(P) data.address;
         return ret;
     }

```

Now the compiler will correctly identify your `main` as illegal:
```
onlineapp.d(43): Error: cannot implicitly convert expression 
`p.ptr()` of type `int*` to `immutable(int*)`
```


More information about the Digitalmars-d mailing list