DIP74: Reference Counted Class Objects

Michel Fortin via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 27 05:48:43 PST 2015


On 2015-02-26 21:50:55 +0000, Andrei Alexandrescu said:

> http://wiki.dlang.org/DIP74 got to reviewable form. Please destroy and discuss.

Looks good in general.

Somehow I can't help but think how overloading new and delete would be 
useful in combination with this. You know, this feature from D1 that 
was deprecated for some reason (but still work fine as far as I know)?
http://digitalmars.com/d/1.0/class.html#allocators

	class MyRCObject
	{
		new(size_t size) { return malloc(size); }
		delete(void* ptr) { free(ptr); }

		private size_t refs = 1;
		void opAddRef() { ++refs; }
		void opRelease() { if (--refs == 0) delete this; }
	}

This way the user doesn't have to check the documentation for the 
correct way to allocate this class, `new` will "just work":

	auto obj = new MyRCObject;

It's not like the user really has any choice in how to allocate the 
object anyway: implicit calls to `opRelease` will make sure things 
break if you use a different allocation method than what it expects.

 - - -

In your example with a payload, I think it is bad style to free the 
payload in opRelease. I understand you can't free the payload in the 
destructor to account for the case the destructor is called by the GC, 
but that pattern won't work if you create a class derived from Widget 
adding another similar payload. Just saying.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list