Avoid infinite recursion in destructor
7
As part of an exercise my university has tasked me with, I have written a small Graph implementation, following this header.
class Node {
private:
std::string name;
std::vector<Node*> children;
public:
Node(const std::string& name="");
virtual ~Node();
}
When writing code for the destructor ~Node()
, I noticed that my implementation fails when the graph contains a cycle. This is my implementation so far, which obviously doesn't work if the graph contains a cycle.
Node::~Node() {
for (Node* n : children) {
delete n;
n = NULL;
}
children.clear();
}
I am uncertain as to how I would most elegantly write a destructor that can handle cycles in the graph?
Please note that I was specifically tasked to write a recursive destructor. Thank you for your answers!
recursion graph c++14 destructor
children
in~Node
. 2. Let a higher level function/class manage the destruction of all theNode
s in the graph. – R Sahu 16 hours agodelete
ing it) as well as potentially circular ownership. This is not a trivial problem. You should change your ownership scheme, store yourNode
s in some sort ofGraph
object, and have only theGraph
object be responsible for destroying everyNode
it contains. Remember to useunique_ptr
instead of raw pointers (std::unique_ptr<T>
vsT*
) when a pointer own an object. – François Andrieux 16 hours ago