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
childrenin~Node. 2. Let a higher level function/class manage the destruction of all theNodes in the graph. – R Sahu 16 hours agodeleteing it) as well as potentially circular ownership. This is not a trivial problem. You should change your ownership scheme, store yourNodes in some sort ofGraphobject, and have only theGraphobject be responsible for destroying everyNodeit contains. Remember to useunique_ptrinstead of raw pointers (std::unique_ptr<T>vsT*) when a pointer own an object. – François Andrieux 16 hours ago