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.