使用unique_ptr<>实现列表?
Implementing a list with unique_ptr<>?
据我了解,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
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- EASTL矢量<向量<int>>连续的
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改