draft proposal for ref counting in D

Walter Bright newshound2 at digitalmars.com
Wed Oct 9 19:16:13 PDT 2013


Michel Fortin Wrote:

Le 27-juin-2013 à 18:35, Michel Fortin a écrit :

 > 	class MyObject
 > 	{
 > 		// user-implemented
 > 		static void opRetain(MyObject var);  // must accept null
 > 		static void opRelease(MyObject var); // must accept null
 >
 > 		// optional (showing default implementation below)
 > 		// this can be made faster with for some implementations of ref-counting
 > 		// only call it for an assignment, not for constructing/destructing the pointer
 > 		// (notably for Objective-C)
 > 		static void opPtrAssign(ref MyObject var, MyObject newVal) {
 > 			opRetain(newVal);
 > 			opRelease(var);
 > 			var = newVal;
 > 		}
 > 	}
 >
 > This maps 1 on 1 to the underlying functions for Objective-C ARC.


Actually, I made a small error in opRetain. To match Objective-C ARC it should 
return the retained object:

	static MyObject opRetain(MyObject var);  // must accept null

and the default implementation for opPtrAssign would then become:

	static void opPtrAssign(ref MyObject var, MyObject newVal) {
		newVal = opRetain(newVal);
		opRelease(var);
		var = newVal;
	}

One reason is that Objective-C blocks (equivalent of delegate literals) are 
stack allocated. If you call retain on a block, it'll make a copy on the heap 
and return that copy.

Another reason for opRetain to return the object is to enable tail-call 
optimization for cases like this one:

	NSObject x;

	NSObject getX() {
		return x; // D ARC should insert an implicit opRetain here
	}

Of course it doesn't necessarily need to work that way, but it'd certainly make 
it easier to integrate with Objective-C if it worked that way.



More information about the Digitalmars-d mailing list