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. This progress has in turn enabled the creation of SafeRefCounted
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 (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.