Manual Deletion from Destructor

dsimcha dsimcha at yahoo.com
Sat Mar 14 08:53:17 PDT 2009


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.



More information about the Digitalmars-d mailing list