RFC: safe ref counting

ikod geller.garry at gmail.com
Sat May 2 08:02:43 UTC 2020


On Saturday, 2 May 2020 at 02:27:10 UTC, Steven Schveighoffer 
wrote:
> In trying to make iopipe @safe, I came to the realization that 
> having auto-managed items such as files and the like (std.io 
> Files and Sockets are non-copyable), you need to rely on some 
> form of @safe reference counting. Unfortunately 
> std.typecons.RefCounted is not and cannot be safe. This is 
> because it allocates in the C heap, and deallocates regardless 
> of whether anyone has ever squirreled away a reference.
>
> So I thought I'd make a refCounted struct that uses the GC [1]. 
> The concept is simple -- allocate the refCounted payload in a 
> GC block, then pin the block as a root. Once all references are 
> gone, remove the root. But the memory stays behind to keep 
> things memory safe (if, for example, you saved a pointer to it 
> outside a reference count object). The memory will be in an 
> initial state, but not invalid.
>
> This means that if you include it in e.g. an array or a class, 
> then it still should work correctly (the memory is guaranteed 
> to be present, and anything it points at).
>
> Of course, you can have cycles that prevent it ever from being 
> cleaned up. But most of the time, this is for auto cleaning up 
> stack items. So maybe that's OK?
>
> Let me know what you think. It sucks that we have no valid way 
> to do reference counting in safe code, because std.io and 
> iopipe highly depend on it.

For my small memory buffer mgmt library I use next solution - 
library user can't have raw pointers to memory (I understand this 
is not your case with file etc), It can only have
unique_ptr to the mutable memory chunk which user can fill with 
some data(from file/network), and also can convert this 
unique_ptr to ref_counted (to immutable view of this memory), and 
this destroys uniq_ptr, so it can't be used anymore. It is safe 
to keep ref_counted in arrays.

PS. it is better to make things @nogc from beginning

>
> -Steve
>
> [1] 
> https://github.com/schveiguy/iopipe/blob/makesafe/source/iopipe/refc.d




More information about the Digitalmars-d mailing list