Challenge: write a reference counted slice that works as much as possible like a built-in slice

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Nov 12 22:01:59 UTC 2021


On Fri, Nov 12, 2021 at 10:14:28PM +0100, Timon Gehr via Digitalmars-d wrote:
> On 12.11.21 18:44, H. S. Teoh wrote:
> > Yes.  So actually, this*could*  be made to work if the RC payload is
> > only allowed to be allocated from an RC allocator.  The allocator
> > would allocate n+8 bytes, for example, and return a pointer to
> > offset 8 of the allocated block, which is cast to whatever
> > type/qualifier(s) needed.  Offset 0 would be the reference count.
> > The copy ctor would access the reference count as *(ptr-8), which is
> > technically outside the const/immutable/whatever payload.  When the
> > ref count reaches 0, the allocator knows to deallocate the block
> > starting from (ptr-8), which is the start of the actual allocation.
> 
> You still need language support. Reaching mutable data through an
> immutable pointer violates transitivity assumptions.

Aside from the technicalities of storing the refcount in the machine
word preceding the allocated block, one could imagine this as looking up
(and updating) state in a global AA using the address of the immutable
ref.

Definitely impure, though, 'cos if we want to remain consistent with the
global AA analogy, we have to consider the refcount as global state, so
we cannot do this kind of refcounting in pure code.


T

-- 
Life begins when you can spend your spare time programming instead of watching television. -- Cal Keegan


More information about the Digitalmars-d mailing list