C++ mutable in D
Paul Backus
snarwin at gmail.com
Tue Aug 3 16:08:54 UTC 2021
On Tuesday, 3 August 2021 at 15:33:34 UTC, Dukc wrote:
> On Tuesday, 3 August 2021 at 14:01:20 UTC, Paul Backus wrote:
>> https://issues.dlang.org/show_bug.cgi?id=1983
>
> I don't think it's that one. I'm not abusing the delegates
> context pointer mutablity, I'm abusing the fact that a `const`
> or `immutable` `delegate` may have a mutable return type:
>
> ```d
> @safe:
>
> void main()
> { import std;
> auto varArr = [5];
>
> immutable del = () => varArr[0];
> del().writeln;
> varArr[0] = 10;
> del().writeln;
> }
> ```
This example is abusing the fact that an `immutable` delegate can
have a mutable context pointer--i.e., that immutability of
delegate contexts is not transitive. If you try to replace the
delegate with a user-defined type...
```d
struct Delegate
{
int* context;
this(int* p) { context = p; }
int opCall() { return *context; }
}
void main()
{
int* p = new int(5);
immutable dg = Delegate(p);
}
```
The compiler correctly points out that the conversion to
`immutable` is invalid:
> Error: cannot implicitly convert expression
> `Delegate(null).this(p)` of type `Delegate` to
> `immutable(Delegate)`
You're right, though, that it's not exactly issue 1983. I think
the bugzilla issue for this specific case is
https://issues.dlang.org/show_bug.cgi?id=16058.
More information about the Digitalmars-d
mailing list