Manual Deletion from Destructor

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sat Mar 14 09:32:49 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.

You can't call delete against a struct object, so the above wouldn't 
compile. What may solve your problem is calling GC.hasNoPointers against 
the block of memory in which hugeDataStructure lives. But before that... 
isn't the current GC non-conservative for heap-allocated objects? I 
thought it's only conservative for stack objects.

Andrei



More information about the Digitalmars-d mailing list