Allocator-aware @safe reference counting is still not possible
Timon Gehr
timon.gehr at gmx.ch
Mon Jan 30 01:07:32 UTC 2023
On 1/28/23 16:56, Nick Treleaven wrote:
> On Sunday, 22 January 2023 at 15:28:53 UTC, Atila Neves wrote:
>> I'm pretty much convinced we need isolated. This is very similar to
>> why the language as it exists today doesn't allow a library author to
>> write a vector type that can be appended to, which... is the main
>> reason one would use a vector to begin with.
>>
>> Some allocators (GC?) might have a @safe deallocate function but most
>> (all except the GC?) can't due to aliasing, and that requires isolated.
>
> `isolated` would be nice, but for now we can model it with a struct so
> that this works:
> ```d
> class Mallocator : IAllocator
> {
> import core.stdc.stdlib : free, malloc;
>
> void* safeAllocate(size_t n) @trusted
> {
> return malloc(n);
> }
>
> void safeDeallocate(Isolated!(void*) ip) @trusted
> {
> ip.unwrap.free;
> }
> }
>
> void main()
> {
> IAllocator a = new Mallocator;
> scope m = a.safeAllocate(4);
> auto ip = (() @trusted => assumeIsolated(a.safeAllocate(4)))();
> a.safeDeallocate(ip.move);
> assert(ip.unwrap == null);
> }
> ```
> Working code:
> https://github.com/ntrel/stuff/blob/master/typecons/isolated.d
>
> Isolated could go in std.typecons.
Isolated is not sufficient, you also have to guarantee the pointer was
allocated with `malloc`.
More information about the Digitalmars-d
mailing list