Object Pointer

Jonathan M Davis jmdavisProg at gmx.com
Mon Jul 16 01:46:42 PDT 2012


On Monday, July 16, 2012 10:31:11 Namespace wrote:
> I'm just experiement with D, that's all. ;)
> Most of my questions here are just out of curiosity.
> 
> I have now this construct:
> 
> [code]
> class smart_ptr {
> private:
> 	A* _ptr;
> 
> public:
> 	this(A* ptr) {
> 		void* buffer = GC.malloc(A.sizeof);
> 		memcpy(buffer, ptr, A.sizeof);
> 
> 		this._ptr = cast(A*) buffer;
> 	}
> 
> 	~this() {
> 		GC.free(this._ptr);
> 	}
> 
> 	@property
> 	A* Ptr() {
> 		return this._ptr;
> 	}
> 
> 	alias Ptr this;
> }
> [/code]
> 
> And that is how i use it (ATM):
> 
> [code]
> A a = new A(42);
> smart_ptr sptr = new smart_ptr(&a);
> sptr.echo();
> 
> a = null;
> 
> sptr.echo();
> [/code]
> 
> But how can i free the memory?
> Bizarrely it cannot be delete in the dtor. o.O
> Strange design.

You can't do _anything_ which would allocate or free GC memory in a class 
destructor/finalizer. And even _using_ the GC heap in a class' finalizer is a 
_bad_ idea, because anything to which the object refers to with its member 
variables which is on the GC heap (be it directly or indirectly) may already 
have been collected by the GC (otherwise, it would have problems with circular 
references).

But if you're allocating on the GC heap, you don't _need_ to free anything. 
The GC does that. Class finalizers are for managing resources _other_ than GC 
memory.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list