Signals and Slots in D

Lionello Lunesu lio at lunesu.remove.com
Fri Sep 29 08:15:34 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 think my other reply addresses the wrong issue, but I still think we 
can use RAII + c-heap. We just need 1 extra indirection:

class Test {
	~this() { printf("~Test\n"); }
}

class WeakPtr(T) {
	private T* _ptr;
	this() { _ptr = cast(T*)std.c.stdlib.malloc(_ptr.sizeof); }
	~this() { printf("~WeakPtr\n"); std.c.stdlib.free(_ptr); }
	T ptr() { return *_ptr; }
	T ptr(T p) { return *_ptr = p; }
}

void main() {
	auto weak = new WeakPtr!(Object);
	auto object = new Test;
	weak.ptr = object;
	object = null;
	printf("%i\r",0);// do some stuff
	std.gc.fullCollect(); // collects object
	assert(weak.ptr !is null);
	weak = null;
	std.gc.fullCollect(); // collects weakptr
}

 >dmd -debug -run weakref.d
~Test
~WeakPtr

(not working in release; probably there's a ref left on the stack somewhere)

L.



More information about the Digitalmars-d mailing list