Slow recursive destructor call in C++
<p>I am using C++ do represent large graphs using reference counted objects. Something like:</p>

<pre><code>// Public class
class Pointer{
  public:
  // Constructors
  Pointer(...){ node = ...; node-&gt;counter++;}

  // Copy constructor
  Pointer(Pointer&amp; const other){ node = other.node; node-&gt;counter++;}

  // Destructor
  ~Point(){ if(--node-&gt;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];
};
</code></pre>

<p>There is thus a public class <code>Pointer</code> which contains a pointer to a polymorphic class Node. Some classes derived from Node will contain new <code>Pointer</code> instances. Note that several <code>Pointer</code> instances may point to the same <code>Node</code> instance. </p>

<p>I use this class to build up very large graphs with millions of instances, and this works fine. The problem comes when the graph is to be deleted. With the default destructor implementation this results in a stack overflow, since in the destructor of the root node, the destructors of the children are called and in the children's destructors, the destructors of the children of the children are called and so on.</p>

<p>I solved this by implementing a destructor for the <code>NodeDerived</code> class above that avoids the recursive call by using a stack instead. This works, but is still very slow, and I am looking for a way to speed this up. Is it possible to somehow avoid declaring the destructor <code>virtual</code> without causing a memory leak?</p>
