Hi everyone,
I'm coding a binary search tree. I have a question about the following struct Node, which I have seen has been implemented this way:
1 2 3 4 5 6 7 8
|
template <typename T>
struct Node{
T data;
std::unique_ptr<Node<T>> left;
std::unique_ptr<Node<T>> right;
Node<T>* parent;
};
| |
Here (and on lots of sites) the left and right children are a
std::unique_ptr
to a Node. I have some issues on "describing" this choice.
- Why should I prefer a unique pointer instead of a raw one for the children? I know that I can use only raw pointers, but I want to grasp the basic motivation of using unique pointers in this case.
For instance, if I say
std::unique_ptr<Node<T>> left{my_node};
I mean that
left
owns a raw pointer to the node
my_node
and the "uniqueness" comes from the fact that
left
owns the object pointed to, which is the node
my_node
.
- Why can't be the parent a unique_ptr too? I've read somewhere that I somewhat loose the uniqueness, but I can'y figure out what this means.
Let's say I have a node with value
8
, with left child
3
, and the right child of
3
is
6
. If each parent is a unique_ptr, then I would have (for instance) that the parent of node
6
should be a unique_prt to
3
, which is already "uniquely" owned by the left child of node
8
and hence I have a conceptual conflict, in some sense.
I don't think my argument above is correct, so any help is highly appreciated!