Reddit: SafeD - The Safe Subset of D

e-t172 e-t172 at akegroup.org
Mon Mar 31 03:44:54 PDT 2008


Kevin Bealer a écrit :
> There are some ways to work around this though -- If object A needs
> to call B.close(), then a reference to object B can be stored in a
> global (or static) variable as well as in object A.  After object A's
> destructor calls B.close(), then it should remove B from the global
> table, thus making B garbage (B will not actually get freed until the
> next GC cycle.)  (Make sure the table doesn't need to synchronize for
> the "remove" step since that could cause deadlock, so an associative
> array is probably a bad idea.)

What about this solution:

class Parent
{
	private Child mychild;

	this()
	{
		mychild = new Child();
		addRoot(mychild);
	}

	~this()
	{
		mychild.close();
		removeRoot(mychild);
	}
}

That would not destroy mychild until the Parent object destructor is 
called. One could even add "delete mychild" at the end of ~this to make 
it even more efficient, if we suppose that mychild is useless anyway 
without its Parent (which is often the case, consider a I/O object, i.e. 
a socket, attached to a "parent" that control it).

The downside of this solution is that you're basically falling back to 
manual memory management (sort of), but I don't think it is avoidable.

By the way, I never understood why the I/O objets in Phobos and Tango 
(i.e. FileConduit) do not automatically close() themselves in their 
destructors... that would solve the problem in the majority of cases.


More information about the Digitalmars-d-announce mailing list