RCArray is unsafe

via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 3 09:40:58 PST 2015

On Tuesday, 3 March 2015 at 17:00:17 UTC, Zach the Mystic wrote:
> On Tuesday, 3 March 2015 at 16:31:07 UTC, Andrei Alexandrescu 
> wrote:
>>> I was dazzed, but I'm not anymore. I wrote my concern here:
>>> http://forum.dlang.org/post/ylpaqhnuiczfgfpqjuww@forum.dlang.org
>> There's a misunderstanding here. The object being assigned 
>> keeps a trailing list of past values and defers their 
>> deallocation to destruction. -- Andrei
> So you need an extra pointer per instance? Isn't that a big 
> price to pay?

All instances need to carry a pointer to refcount anyway, so the 
freelist could just be stored next to the refcount. The idea of 
creating that list, however, is more worrying, because it again 
involves allocations. It can get arbitrarily long.

> Is the only problem we're still trying to solve aliasing which 
> is not recognized as such and therefore doesn't bump the 
> refcounter like it should? An extra pointer would be overkill 
> for that. Isn't it better to just recognize the aliasing when 
> it happens?
> As far as taking the address of an RcArray element, the type of 
> which element is not itself Rc'ed, it's a different problem. 
> The only thing I've been able to come up with is maybe to 
> create a wrapper type within RcArray for the individual 
> elements, and have that type do refcounting on the parent 
> instead of itself, if that's possible.

No, Andrei's proposed solution would take care of that. On 
assignment to RCArray, if the refcount goes to zero, the old 
array is put onto the cleanup list. But there can still be 
borrowed references to it's elements. However, these can never 
outlive the RCArray, therefore it's safe to destroy all of the 
arrays in the cleanup list in the destructor.

More information about the Digitalmars-d mailing list