Improving DIP74: functions borrow by default, retain only if needed

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 27 13:15:31 PST 2015


On 2/27/15 12:34 PM, Steven Schveighoffer wrote:
> On 2/27/15 3:30 PM, Steven Schveighoffer wrote:
>
>> void main()
>> {
>> C c = new C; // ref counted class
>> C2 c2 = new C2; // another ref counted class
>> c2.c = c;
>> foo(c, c2);
>> }
>
> Bleh, that was dumb.
>
> void main()
> {
>     C2 c2 = new C2;
>     c2.c = new C;
>     foo(c2.c, c2);
> }
>
> Still same question. The issue here is how do you know that the
> reference that you are sure is keeping the thing alive is not going to
> release it through some back door.

Thanks! In ARC, there are autorelease pools that keep at least one 
reference to the objects they own. I think that's what they are for.

So let me add a complete example:

class C {
    void someFunc();
    void opAddRef();
    void opRelease();
}

class C2 {
    C c;
    void opAddRef();
    void opRelease();
}

void foo(C c, C2 c2) {
    c2.c = null;
    c.someFunc(); // crash
}

void main() {
    C2 c2 = new C2;
    c2.c = new C;
    foo(c2.c, c2);
}

Distinguishing these is an interesting problem. In fact we can reduce 
the matter to one class only:

class C {
    C c;
    void someFunc();
    void opAddRef();
    void opRelease();
}

void foo(C c1, C c2) {
    c2.c = null;
    c1.someFunc(); // crash
}

void main() {
    C obj = new C;
    obj.c = new C;
    foo(obj.c, obj);
}


Andrei



More information about the Digitalmars-d mailing list