Signals and Slots in D

Lionello Lunesu lio at lunesu.remove.com
Fri Sep 29 07:35:35 PDT 2006


Thomas Kuehne wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Lionello Lunesu schrieb am 2006-09-29:
>> Thomas Kuehne wrote:
>>> Walter Bright schrieb am 2006-09-29:
>>>> The problem in general with hiding pointers is that it'll break with a 
>>>> moving garbage collector. You could work around this by 'pinning' the 
>>>> objects, but pinning objects long term is a bad idea.
>>> How about an GC allocation area that isn't searched for valid pointers
>>> but is still collected?
>> Couldn't we use malloc/free + RAII for that? ...auto_ptr<>?
> 
> No. The trick is that this area is collected(and updated by a moving
> GC), but isn't considered while looking for pointers into the "normal"
> area.

I've been experimenting a bit and got up with the attached stuff.

I copy-pasted 'main' here to explain my point. SafePtr is a template 
class that wraps a pointer. It has custom (de)allocator using 
malloc/free, so it's not scanned by GC.

I create an object, Test, on the heap and have just one reference to it, 
the one on the stack. I also set the pointer in the SafePtr instance to 
that same object, but that occurence of the pointer is not scanned so 
doesn't count. When settings the reference to the object to null (and 
forcing a full collect cycle) the GC _will_ collect the object 
(eventhough we still had another reference to it in SafePtr).

As for the notification, the Test class keeps a list of pointers to 
IOnDelete, which it iterates in its destructor. SafePtr implements 
IOnDelete.OnDelete and resets its reference.

L.

void main()
{
	auto SafePtr!(Test) x = new SafePtr!(Test);
	Test test = new Test;
	// Let the safe-pointer point to the test object
	x.ptr = test;
	// Now remove the (last) reference to the test object
	test = null;
	// We must do some operation here to get rid of any references on the stack
	printf("%p\r",test);		// overwrite stack
	// Let the GC do a full collect (will collect the test object)
	std.gc.fullCollect();
	// The safe-pointer will have been notified
	if (!x.ptr)
		printf("Target was deleted by GC\n");
}
-------------- next part --------------
A non-text attachment was scrubbed...
Name: weakref.zip
Type: application/octet-stream
Size: 1514 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20060929/ea4ba986/attachment.obj>


More information about the Digitalmars-d mailing list