I use C ++, represent large graphs using counted objects. Sort of:
// Public class class Pointer{ public: // Constructors Pointer(...){ node = ...; node->counter++;} // Copy constructor Pointer(Pointer& const other){ node = other.node; node->counter++;} // Destructor ~Point(){ if(--node->counter==0) delete node;} // Other methods ... Node* node; }; // Node base class class Node{ // Constructor Node():counter(0){} // Destructor virtual ~Node(){} // public: unsigned long counter; }; // Node derived class class NodeDerived : public Node{ // Constructors and other methods ... // Destructor virtual ~NodeDerived(){ ... } // Children Pointer children[2]; };
Thus, there is an open Pointer class that contains a pointer to a polymorphic Node class. Some classes derived from Node will contain new instances of Pointer . Note that multiple Pointer instances may point to the same Node instance.
I use this class to create very large graphs with millions of instances, and this works great. The problem arises when the graph needs to be deleted. Thanks to the default destructor implementation, this leads to a stack overflow, since child destructors are called in the node root destructor and child destructors of the children are called in the destructors of the children, etc.
I solved this by implementing a destructor for the NodeDerived class above, which avoids a recursive call using the stack instead. It works, but still very slow, and I'm looking for a way to speed it up. Is it possible to somehow avoid declaring a virtual destructor without causing a memory leak?
source share