I'm building a tree with Node class having unique_ptr on the left and right child and Node* pointer to parent. When I'm deleting nodes, I take node and the I have to check if the node i'm deleting is right of left child and then reset the unique_ptr in the parent. Is there any way to take the pointer and ask if there is any unique_ptr wrapper around it and possibly return it?
0
votes
2 Answers
5
votes
Is there any way to take the pointer and ask if there is any unique_ptr wrapper around it and possibly return it?
There's no generic way to find the unique_ptr
, but you can for example store a reference.
Assuming your tree is binary, you can find the unique_ptr
in parent like this:
(parent->left == this ? parent->left : parent->right).release();
If the tree isn't binary, you can iterate over all children.
0
votes
In C++, pointers are uni-directional; and unique_ptr
, being simply a wrapper class around a pointer, doesn't change that. There is no way to get the unique_ptr
from the raw pointer it is pointing to.
A few alternative solutions to your particular issue are possible:
- Add a parent pointer to the child object, then you can navigate to the parent to delete the child from there. This may be inefficient if you have a lot of nodes.
- Implement the concept of an iterator - an abstraction of a context that carries sufficient information to be able to modify the tree (e.g. delete a node). For example, a tree iterator could contain a pointer to the current node, a pointer to its parent and the flag indicating if it's a left or right child. The downside is that you can't modify a tree simply by having a pointer to its node, you need to have an instance of an iterator.
std::shared_ptr
usingstd::/enable_shared_from_this
. – François Andrieuxif (this->parent->left.get() == this) { // current node is left child } else { // is right }
. – Nir Friedmaniterator
type contain a pointer to theunique_ptr
to the Node in question, rather than directly to the node. Either way you'll need to access the parent held pointer and there's no magic way to do that. Note that Francois' suggestion of enable_shared_from_this doesn't help you either. – Nir Friedman