I'm trying to design a tree class in C++, but I'm running into some trouble with node destruction.
If I destroy a node, I don't want to destroy it's entire sub-tree because there might be something else pointed to it. So the obvious solution is the use reference counting. I'd have a weak pointer to the parent, and a vector of shared pointers to the child nodes. That way if a node is destroyed, it's children are only destroyed if nothing is pointing to them.
But I run into another problem here: adding a child to a node. weak_ptr only works if there's already a shared_ptr pointing to an object. And if I adding a child to a node, I don't know where to find a shared_ptr that's pointing to it. So what do I do here?
You might want to look into enable_shared_from_this
that allows you to obtain the shared_ptr
directly from the object. It still requires that the object is managed by a shared_ptr
, but you don't need to find who is holding it.
To expand on David Rodriguez's idea, a skeleton tree might look like this:
struct node : std::enable_shared_from_this<node>
{
std::vector<std::shared_ptr<node>> children;
std::weak_ptr<node> parent;
void add_child()
{
auto n = std::make_shared_node>();
n->parent = std::weak_ptr<node>(shared_from_this());
children.emplace_back(n);
}
}
auto root = std::make_shared<node>();
root.add_child();
root.add_child();
root.add_child();
root.children[0].add_child();
(Of course a real-world node
would have a non-trivial constructor with payload values, and add_child
would take similar arguments or be a template...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.