RCArray is unsafe

Zach the Mystic via Digitalmars-d digitalmars-d at puremagic.com
Wed Mar 4 10:28:30 PST 2015

On Wednesday, 4 March 2015 at 18:05:52 UTC, Zach the Mystic wrote:
> On Wednesday, 4 March 2015 at 17:22:15 UTC, Steven 
> Schveighoffer wrote:
>> Again, I think this is an issue with the expectation of 
>> RCArray. You cannot *save* a ref to an array element, only a 
>> ref to the array itself, because you lose control over the 
>> reference count.
> What you need is a special RCSlave type, which is reference 
> counted not to the type of its *own* data, but to its parent's. 
> In this case, a RCArraySlave!(T) holds data of type T, but a 
> pointer to an RCArray, which it decrements when it gets 
> destroyed. This could get expensive, with an extra pointer per 
> instance than a regular T, but it would probably be safe.

Another solution is to get compiler help. If you know the 
lifetime of a sub-reference `p.t` to be shorter than of its Rc'd 
parent `p`, the compiler can wrap its `p.t's lifetime in an 
addRef/release cycle for P. This works in calling a function:

fun(p, p.t);

Let's say that you know that `p.t` won't escape (a different 
question). The compiler doesn't need to know about `p.t` to wrap 
the whole function like this:

p.opAddRef(); // or equivalent
fun(p, p.t);

It just needs to know that `p.t's lifetime is shorter than `p's.

More information about the Digitalmars-d mailing list