Smart pointer for single owner and multiple links

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(); // <-- what type should node be??
while(node) {
  if (node->left_count < node->right_count) {
    node = node->left_child_.get();
  } else {
    node = node->right_child.get();
  }
}
// do something on node

. , node ? , . , weak_ptr, , , shared_ptr, , shared_ptr. .

:

class LinkedList {
  std::unique_ptr<Node> first_;
  /** ?? type ?? **/ last_;
}


for (/*?? type ??*/ n = first_; n != last_; n = n->next) {
}

, raw- ( , ++), , ( ): , , A smart pointer .

+4
1

, . , , , . , shared_ptr weak_ptr. , , , , .

- unique_ptr , , unique_ptr:: get. , proxy_ptr - : proxy_ptr p = make_proxy (yourUniquePtr.get());

+1

Source: https://habr.com/ru/post/1538212/


All Articles