RCArray is unsafe

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Wed Mar 4 10:17:41 PST 2015


On 3/4/15 9:22 AM, Steven Schveighoffer wrote:
> On 3/4/15 10:42 AM, Andrei Alexandrescu wrote:
>> On 3/4/15 12:55 AM, Ivan Timokhin wrote:
>>> Excuse me if I miss something obvious, but:
>>>
>>>      void main()
>>>      {
>>>          auto arr = RCArray!int([0]);
>>>          foo(arr, arr[0]);
>>>      }
>>>
>>>      void foo(ref RCArray!int arr, ref int val)
>>>      {
>>>          {
>>>              auto copy = arr; //arr's (and copy's) reference counts
>>> are both 2
>>>              arr = RCArray!int([]); // There is another owner, so arr
>>>                                     // forgets about the old payload
>>>          } // Last owner of the array ('copy') gets destroyed and
>>> happily
>>>            // frees the payload.
>>>          val = 3; // Oops.
>>>      }
>>
>> That's a problem, thanks very much for pointing it out. -- Andrei
>
> 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.
>
> I don't think arr[0] should correctly bind to foo's second argument.

Yah, this is a fork in the road: either we solve this with DIP25 + 
implementation, or we add stricter static checking disallowing two lent 
references to data in the same scope.

Andrei



More information about the Digitalmars-d mailing list