C++ mutable in D
Dukc
ajieskola at gmail.com
Tue Aug 3 13:02:38 UTC 2021
On Friday, 30 July 2021 at 19:17:55 UTC, Michael Galuza wrote:
> [snip]
We are saying that there is no direct analogue for `mutable` in
D. It turns out we were all wrong - there is, and it even works
in `@safe`! Behold:
```d
@safe:
alias MutableDel(T) = @safe ref T delegate();
struct Foo
{ int normalMember;
private MutableDel!int _mutableMember;
ref mutableMember() const {return _mutableMember();}
this(int a, int b)
{ normalMember = a;
_mutableMember = makeMutable(b);
}
}
MutableDel!T makeMutable(T)(T mem) @safe
{ auto varArr = [mem];
return ref () => varArr[0];
}
void main()
{ import std;
const foo = Foo(5, 10);
foo.mutableMember.writeln; //10
foo.mutableMember = 15;
foo.mutableMember.writeln;
}
```
Now, I definitely don't recommend using this. It might well end
up being considered as a bug, and thus stop working in the
future. Also the optimizer might not take this possibility into
account, thus injecting bugs to your code.
More information about the Digitalmars-d
mailing list