ARC on Objects not Class Definitions

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Wed Nov 4 17:42:16 PST 2015


On Wednesday, 4 November 2015 at 19:33:07 UTC, IbanezDavy wrote:
> Usually how you allocate the object has very little to do with 
> implementation of the object itself.

The question isn't really allocation, but instead when to 
deallocate. The object itself needs to know it because the object 
may pass out references to itself.

Consider something like this:

class MyString {
    private char[128] data_;
    private int length_;

    char[] getData() { return this.data_[0 .. length_]; }
}

How you allocate that isn't terribly important. You might malloc 
it, you might gc it, you might stick it on the stack. (This is 
all possible, even easy, with D today btw.)

But, when should it be freed?

char[] getString() {
    MyString s = make!myString;
    return s.getData();
    // does s get freed here? what about the returned member 
though?
}


GC solves it by keeping the object alive if there's any reference 
in living memory, determined by scanning it at collection time.

ARC injects code. If it is just an allocation decision, the 
getData function wouldn't know it needs to increase its reference 
count... and s would be freed too soon, while the data is still 
propagated.

The object would need to be aware either to a) don't do that, 
make it an error to return a reference to itself, or b) add some 
refcounting-aware type to the return value too.


You can get by without that stuff if you leave matters all in the 
programmer's hands, but the point of @safe is to take it out fo 
your hands and into the compiler's.


More information about the Digitalmars-d mailing list