使用unique_ptr<>实现列表?

Implementing a list with unique_ptr<>?

本文关键字:gt 列表 实现 lt unique ptr 使用      更新时间:2023-10-16

据我了解,unique_ptr表示独家所有权。单链表似乎符合这一点,每个节点都拥有下一个节点,例如(pseduocode alert)

class node{
public:
      unique_ptr<node> next;
      int value;
};

但是我不明白如何执行诸如遍历列表之类的操作,这是我习惯做的事情

here=here->next;

如何使用unique_ptr实现数据结构?它们是适合这项工作的工具吗?

当你通过节点时,你不需要拥有节点指针,这意味着

这里

=这里->下一个;

如果这里是unique_ptr,则不正确。拥有一件物品意味着"对它的生死负责",这意味着拥有将摧毁该物品的代码的人。如果你使用拥有的另一个定义,那么它就不是unique_ptr的意思。

在列表节点代码中,假设每个节点负责下一个节点(如果销毁一个节点,则所有下一个节点也将销毁)。它可以是有效的行为,这取决于你的需求,只要确保这是你真正想要的。

你想要的是读取指针而不拥有它。当前执行此操作的良好做法是使用原始指针向查看此代码的其他开发人员指示"使用但不拥有"类型的用法(unique_ptr表示"如果我死了,指向的对象也会死"):

node* here = nullptr; // it will not own the pointed nodes (don't call delete with this pointer)
here = &first_node(); // assuming first_node() returns a reference to the first node
here = here->next.get(); // to get the next node without owning it: use get() - true in all smart pointers interface