使用unique_ptr <>实现列表?

Ale*_*ene 5 c++ smart-pointers c++11

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

class node{
public:
      unique_ptr<node> next;
      int value;
};
Run Code Online (Sandbox Code Playgroud)

但我不明白如何执行操作,如遍历列表,我过去常常这样做

here=here->next;
Run Code Online (Sandbox Code Playgroud)

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

Kla*_*aim 6

当您浏览节点时,您不需要拥有节点指针,这意味着

这里=这里 - >下;

如果这是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
Run Code Online (Sandbox Code Playgroud)

  • @AlexanderDuchene:智能指针的重点在于他们*定义*谁对他们"负责".如果您希望其他对象对它们负责,则不应使用智能指针. (4认同)