Enhancements can enable memory-safe reference counting
tsbockman
thomas.bockman at gmail.com
Wed May 26 21:28:30 UTC 2021
On Wednesday, 26 May 2021 at 18:53:21 UTC, vitoroak wrote:
> Every time I tried to do something similar in D I stumbled
> across the same problems and as far as I know it's not possible
> to implement it completely @safe today. I think one of the
> problems is that you can manually destroy/move any struct while
> there are still references/pointers to it or its internals like
> in the example below (I used your borrow mixin template).
>
> ```d
> void receiveByValue(Unique!(int*) u) @safe {
> }
>
> void main() @safe {
> import std.stdio: writeln;
>
> auto u1 = Unique!(int*)(true);
> mixin borrow!(u1, "x1");
> writeln(*x1); // ok
> destroy(u1);
> writeln(*x1); // should not be possible
Yes, that is a problem.
Manually calling `destroy` or `__dtor` really should be an
`@system` operation, regardless of the attributes of `__dtor`
itself. The whole point of destructors is to ensure that cleanup
work is performed at the correct point, and potentially
subverting that should not be considered `@safe`.
> ```d
> import core.lifetime: move;
>
> auto u2 = Unique!(int*)(true);
> mixin borrow!(u2, "x2");
> writeln(*x2); // ok
> receiveByValue(move(u2));
> writeln(*x2); // should not be possible
> }
>
> ```
That second test, with `move`, actually doesn't compile (although
I'm not sure why):
```
onlineapp.d(150): Error: @safe function D main cannot call
@system function core.lifetime.move!(Unique!(int*)).move
/dlang/dmd-nightly/linux/bin64/../../src/druntime/import/core/lifetime.d(1587): core.lifetime.move!(Unique!(int*)).move is declared here
```
More information about the Digitalmars-d
mailing list