RCArray is unsafe
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Mon Mar 2 12:37:55 PST 2015
On 3/1/15 2:21 PM, Walter Bright wrote:
> On 3/1/2015 7:44 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm at gmx.net>"
> wrote:
>> A weakness of the same kind affects DIP25, too. The core of the
>> problem is
>> borrowing (ref return as in DIP25), combined with manual (albeit
>> hidden) memory
>> management. An example to illustrate:
>>
>> struct T {
>> void doSomething();
>> }
>> struct S {
>> RCArray!T array;
>> }
>> void main() {
>> auto s = S(RCArray!T([T()])); // s.array's refcount is now 1
>> foo(s, s.array[0]); // pass by ref
>> }
>> void foo(ref S s, ref T T) {
>> s.array = RCArray!T([]); // drop the old s.array
>> t.doSomething(); // oops, t is gone
>> }
This is an odd example, how does one take a ref to an RCArray element
without the machinery to retain the array? I would think that RCArray[x]
would return something that isn't passable to a function. Or am I
missing something?
>
> The trouble seems to happen when there are two references to the same
> object passed to a function. I.e. there can be only one "borrowed" ref
> at a time.
Not exactly. Note that we are taking by reference S, which is NOT
reference counted. So you are passing indirectly a reference to an RC
object. You aren't "borrowing" that reference.
-Steve
More information about the Digitalmars-d
mailing list