[Dlang-study] [lifetime] Initial thoughts on lifetime management

Andrei Alexandrescu andrei at erdani.com
Tue Oct 27 17:45:00 PDT 2015


Hello all and thanks for your interest in the topic of lifetime 
management of D objects. This post outlines a starting point for the 
discussion.

We need for D a form of shared ownership that is not backed up by a 
tracing garbage collector, and one obvious choice is reference counting.

I have argued with simple examples 
(http://forum.dlang.org/thread/n0nnu0$1tth$1@digitalmars.com) that safe 
reference counting cannot be implemented as a library. So we're looking 
at a language-backed solution.

Here there are two options we discussed - an @rc attribute, or simple 
detection of a pair such as opInc/opDec. I've argued for the latter but 
Walter made a good argument for @rc: it gives the compiler complete 
control over "as-if" style optimizations. So I'll proceed under the 
assumption that we go with @rc. Namely, we're looking at:

@rc class Widget {
    ...
}

Such classes:

* do not inherit Object. (Do we want a root of all @rc classes called 
RCObject?)

* cannot be converted to interfaces (we may later add @rc interfaces)

* embed an implementation-defined reference count as a hidden member

* have a vptr only if they define non-final methods (in particular, I 
think we should disable "synchronized" for them - it seems an 
unnecessary complication at least for v1)

* should they have a hidden pointer to the parent scope if nested?

Each reference to the class behaves as-if there is a corresponding bump 
in reference count for it. This is maximally conservative, meaning even 
method calls need to make sure there's a refcount bump for "this". Consider:

Widget global;
@rc class Widget {
   int x;
   void fun() {
     global = null;
     ++x;
   }
}

void main() {
   global = new Widget;
   global.fun();
}

In this example, if global has a refcount==1 upon entering fun(), the 
assignment "global = null" deletes the Widget object and ++x accesses 
dangling memory.

So my plan is to start maximally conservative - i.e. bump the reference 
count appropriately for every use of the object. Then, we define a 
static analysis that eliminates or fuses together most of these 
increments and decrements. There is much research in this area. I am 
counting on the folks in this group to define this analysis rigorously.


Thanks,

Andrei


More information about the Dlang-study mailing list