draft proposal for ref counting in D

Walter Bright newshound2 at digitalmars.com
Wed Oct 9 19:17:24 PDT 2013


Rainer Schuetze wrote:

On 28.06.2013 00:35, Michel Fortin wrote:
 > So if we return to the core of it, here's the problems that still
 > need solving:
 >
 > 1. Depending on the reference counting scheme implemented, it might
 > be more efficient to have a single operation for an assignment
 > (retain a/release b) operation. I think that should be allowed.

 > 2. If the pointer variable is shared assignment must be atomic (done
 > under a lock, and it must always be the same lock for a given
 > pointer, obviously).

 > 3. If the pointer variable is shared, reading its value must be done
 > atomically with a retain too.

I just had an idea, maybe it is obvious and just distracts, but I thought it 
might be worth sharing:

Instead of defining methods on the class type, we could also redefine the 
reference type. The compiler detects a type declaration "reference_type" in the 
class declaration and replaces all references to that class with that type.

class C
{
     alias shared_ptr!C reference_type;
}

C c = new C;

is lowered to

shared_ptr!C c = new C;

"new C" returns a shared_ptr!C aswell.

It is then up to the implementation of shared_ptr to define what member 
functions to call for reference counting and to deal with proper shared 
semantics in assignments. It can also define whether opCall should increment the 
reference count or not. For most of the needed functionality, struct semantics 
work out-of-the-box.

2 immediate gotchas

- In a class hierarchy, you would want to define the reference_type in the base 
class only, so maybe it has to be a template. I'm not sure implicite casting to 
base class reference type and interfaces can be implemented.

- the implementation of the shared_ptr template will have to be able to deal 
with the "raw" reference, so that might need some type modifier/annotation. I 
think this might also be true for the addRef/release version, if the 
implementation is not just working on the refcount, but is also calling other 
functions.

- To elide redundant reference counting, the compiler will need annotations 
here, too. Move semantics of structs might reduce the number of reference count 
operations already, though.



More information about the Digitalmars-d mailing list