Manual Deletion from Destructor

Chad J gamerchad at __spam.is.bad__gmail.com
Sat Mar 14 09:04:19 PDT 2009


dsimcha wrote:
> I sometimes run into false pointer issues when using very large data
> structures in D.  Often, these data structures are owned by a single class
> instance and do not escape.  In these cases, is it safe to do something like:
> 
> class Foo {
>     // Allocated on GC heap.
>     private HugeDataStructure hugeDataStructure;
> 
>     ~this() {
>         // hugeDataStructure _should_ be GC'd when the Foo instance
>         // is GC'd because hugeDataStructure is guaranteed never
>         // to escape.  It may not be b/c
>         // of false pointer issues.  Delete it manually when instance
>         // of Foo that owns it is GC'd.
> 
>         delete hugeDataStructure;
>     }
> }
> 
> The point is that the destructor for instances of Foo is called by the GC, not
> manually.   The GC may have already realized that hugeDataStructure is not
> reachable.  Does this make the delete statement in the d'tor unsafe, or is it
> still ok?
> 
> Note:  You can assume that hugeDataStructure doesn't have its own destructor,
> so delete just frees memory.

http://www.digitalmars.com/d/2.0/class.html#Destructor
http://www.digitalmars.com/d/1.0/class.html#Destructor
both say:

"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. This rule does not apply
to auto objects or objects deleted with the DeleteExpression, as the
destructor is not being run by the garbage collector, meaning all
references are valid."

I think you are violating that rule.



More information about the Digitalmars-d mailing list