draft proposal for ref counting in D

Walter Bright newshound2 at digitalmars.com
Wed Oct 9 18:45:12 PDT 2013


Michel Fortin wrote:

Le 26-juin-2013 à 5:38, Walter Bright  a écrit :

 > On 6/26/2013 12:19 AM, Rainer Schuetze wrote:
 >>
 >> As Michel also said, the reference count does not have to be in inside the 
object itself, so we might want to allow reference counting on other types aswell.
 >
 > That opens the question of what is the point of other RC types? For example, 
C++ can throw any type - but it turns out that throwing anything but class types 
is largely pointless.

RC is just another garbage collection scheme. You might favor it for its 
performance characteristics, its determinism, or the lower memory footprint.

Or you might need it to interact with foreign code that relies on it (COM, 
Objective-C, etc.), in which case it needs to be customizable (use the foreign 
implementation) or be manually managed.

That's two different use cases. And in the later case you can't use the GC to 
release cycles because foreign code is using memory invisible to the GC. It is 
important to note that when foreign code calls AddRef you don't want the GC to 
collect that object, at least not until Release is called.


 >> I don't think we should force linking this functionality with COM, the 
programmer can do this with a simple wrapper.
 >
 > Yeah, that's Michel's suggestion, and it's a good one.

It could also be done with user attributes:

	void x_init(ref X x);
	void x_destroy(ref X x);
	void x_assign(ref X a, X b); // retains a, releases b

	@arc!(x_init, x_destroy, x_assign)
	class X {}

This way you don't have to check for null in the generated code: the standalone 
function is in charge of that.

Also, this "assign" function here provides good opportunity for optimization in 
the RC implementation because you can update the two reference counts in a 
single operation (in the case where they're stored at the same place and are 
protected by the same lock). It's an improvement over making two separate 
function calls.


 > No. The caller of the function still retains a reference in that thread.

This should also apply to all function arguments. The caller is better placed 
than the callee to elide redundant AddRef/Release pairs, so it should be the one 
in charge of retaining the object for the callee.


 >>> 16. RC objects cannot be const or immutable.
 >>
 >> This is a bit of a downer. If the reference count is not within the object, 
this can be implemented.
 >
 > Also, an exception could be made for the AddRef()/Release() functions.

I'm not too fond of that idea.


More information about the Digitalmars-d mailing list