destructor order

Albin Breen abreen at ea.com
Wed Jan 26 07:53:29 PST 2011


Steven Schveighoffer Wrote:

> See here: http://www.digitalmars.com/d/2.0/class.html#destructors
> 
> "The garbage collector is not guaranteed to run the destructor for all  
> unreferenced objects. Furthermore, the order in which the garbage  
> collector calls destructors for unreference objects is not specified. This  
> means that when the garbage collector calls a destructor for an object of  
> a class that has members that are references to garbage collected objects,  
> those references may no longer be valid. This means that destructors  
> cannot reference sub objects."


Thanks! This means that the GC cannot be trusted to call destructors. I interpret that as "class destructors must be called manually".

Furthermore, The D Programming Language book states that: "...there is no delete operator. (D used to have a delete operator, but it was depre- cated.)" so you can't use that either.

In other words you are left with:
	clear(a);
to manually call the destructor, which will also call the constructor again (this time with no parameters), and possibly (but not certainly) the destructor once more.

To be able to use clear() you will have to enforce RAII using structs (not garbage collected) or finally{} or scope constructs all the way from main in parallel with all your garbage collected code.

All in all, if class destructors cannot be guaranteed to execute by other means than the manual approach then should they be considered a liability? In Phobos std.socket a destructor is used to close() the socket.

/Albin


More information about the Digitalmars-d mailing list