Manual Deletion from Destructor

dsimcha dsimcha at yahoo.com
Sat Mar 14 09:40:16 PDT 2009


== Quote from Andrei Alexandrescu (SeeWebsiteForEmail at erdani.org)'s article
> 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

No, the problem is that there may be things that look like pointers pointing to
internal regions of hugeDataStructure.  For example, let's say hugeDataStructure
is a 100-megabyte array.  It's a pretty big target for false pointers, so even
though the only legitimate reference is from the instance of Foo that owns it,
hugeDataStructure might never get GC'd.  In my specific case, hugeDataStructure is
a large associative array.  A few nodes don't get freed properly, leading to heap
fragmentation and massive memory usage.  (I've created my own AA delete function,
which I know works when not used from a destructor like the above example, see
Bugzilla 2105).



More information about the Digitalmars-d mailing list