Allocator-aware @safe reference counting is still not possible
Paul Backus
snarwin at gmail.com
Sun Sep 25 12:03:08 UTC 2022
D has made a lot of progress recently on memory safety with
`-preview=dip1000`, thanks in no small part to [the work of
Dennis Korpel][1]. This progress has in turn enabled the creation
of [`SafeRefCounted`][2] by Ate Eskola, which will hopefully be
available in the next release of Phobos.
The next logical step on this journey is a version of
`SafeRefCounted` with support for `std.experimental.allocator`.
Unfortunately, this step is where we run into a roadblock.
`SafeRefCounted` is allowed make a `@trusted` call to `free` when
it knows it holds the only pointer to its payload, because it
knows (from the C standard) that `free` will not corrupt memory
when called under those circumstances.
However, an allocator-aware version of `SafeRefCounted` that
calls a generic `Allocator.deallocate` function instead of free
specifically has *literally no idea* what that function will do,
and therefore cannot mark that call as `@trusted`, ever, under
any circumstances.
The only solution is to somehow allow `deallocate` (and by
extension `free`) to have a `@safe` interface on its own—which
isn't possible in the current D language. At minimum, it would
require something like an [`isolated` qualifier][3] (h/t
deadalnix for the link), which would guarantee that a pointer is
the only pointer to a particular block of memory. Some form of
ownership/borrow checking would also work, of course.
In any case, this is not something that can be solved in library
code. A language change is necessary.
[1]:
https://github.com/dlang/dmd/pulls?q=is%3Apr+author%3Adkorpel+is%3Aclosed+scope
[2]: https://github.com/dlang/phobos/pull/8368
[3]:
https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/msr-tr-2012-79.pdf
More information about the Digitalmars-d
mailing list