In the days when I implemented linked lists and trees using raw pointers. When I tried to implement using smart pointers, I ran into the following problem, because I do not know what to use for a pointer that will have only one owner, except for 0 or more references:
An example is a binary tree:
To begin with, nodes should be the only "owners of pointers: nodes live and die with the tree, so it makes sense for me to make them unique_ptr, and not shared_ptr:
class Tree {
std::unique_ptr<Node> root_;
}
class Node {
std::unique_ptr<Node> left_child_, right_child_;
}
And then I had to make such an algorithm:
Node * node = root_.get();
while(node) {
if (node->left_count < node->right_count) {
node = node->left_child_.get();
} else {
node = node->right_child.get();
}
}
. , node ? , . , weak_ptr, , , shared_ptr, , shared_ptr. .
:
class LinkedList {
std::unique_ptr<Node> first_;
last_;
}
for ( n = first_; n != last_; n = n->next) {
}
, raw- ( , ++), , ( ): , , A smart pointer .