RCArray is unsafe

via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 3 05:05:55 PST 2015


On Monday, 2 March 2015 at 22:58:19 UTC, Walter Bright wrote:
> On 3/2/2015 1:09 PM, "Marc =?UTF-8?B?U2Now7x0eiI=?= 
> <schuetzm at gmx.net>" wrote:
>> "I have discovered a marvellous solution, but this post is too 
>> short to describe
>> it."
>
> Fortunately, Fermat (er, Andrei) was able to pass along his 
> dazz idea to me this afternoon, before he expired to something 
> he had to attend to. We were both in the dumps about this 
> problem last night, but I think he solved it.
>
> His insight was that the deletion of the payload occurred 
> before the end of the lifetime of the RC object, and that this 
> was the source of the problem. If the deletion of the payload 
> occurs during the destructor call, rather than the postblit, 
> then although the ref count of the payload goes to zero, it 
> doesn't actually get deleted.
>
> I.e. the postblit manipulates the ref count, but does NOT do 
> payload deletions. The destructor checks the ref count, if it 
> is zero, THEN it does the payload deletion.
>
> Pretty dazz idea, dontcha think? And DIP25 still stands 
> unscathed :-)
>
> Unless, of course, we missed something obvious.

Clever :-) But there are two things:

The object is still accessible after its refcount went to zero, 
and can therefore potentially be resurrected. Probably not a 
problem, but needs to be taken into account, in particular in 
with respect to the freelist. That's tricky, because an object 
can be released and resurrected several times, and care must be 
taken that it will not end up in the freelist and get destroyed 
multiple times. And that hasn't even touched on thread-safety yet.

The bigger problem is that it's relying on a convention. The RC 
wrapper needs to be constructed in a particular way that's easy 
to get wrong and that the compiler has no way to check for us.


More information about the Digitalmars-d mailing list