【发布时间】:2021-12-26 19:17:32
【问题描述】:
我正在尝试通过间接指针来实现链表,它在TED Talk上引入。
我参考felipec's implementation on github并通过原始指针制作了一个版本,这是github link。
这是完整代码的一部分,_find是一个可以找到目标节点的间接指针的函数,即*indirect == target node:
//...
struct Node {
int data;
Node *next;
Node()
: data(0), next(nullptr) {}
Node(int _d, Node *_next = nullptr)
: data(_d), next(_next) {}
~Node() { puts("~Node"); }
};
//...
List::Node **List::_find(const int target)
{
Node **indirect = &head;
while (*indirect && (*indirect)->data != target)
indirect = &(*indirect)->next;
return indirect;
}
我想做一个智能指针版本。我在Node 中使用std::unique_ptr 作为next 指针,在List 中使用std::shared_ptr 作为head 指针。
但是在Node **indirect = &head部分,我不知道如何通过智能指针来设计它,我写了这个:
//...
struct Node {
int data;
std::unique_ptr<Node> next;
Node()
: data(0), next(nullptr) {}
Node(int _d, std::unique_ptr<Node> &_next)
: data(_d), next(std::move(_next)) {}
~Node() { puts("~Node"); }
};
//...
List::Node **List::_find(const int target)
{
Node **indirect = &(head.get());
while (*indirect && (*indirect)->data != target)
indirect = &(*indirect)->next;
return indirect;
}
显然,Node **indirect = &(head.get()) 不是一个好主意,因为 get 函数返回它指向的右值。但是我需要的是指向目标的指针对象,代码甚至无法编译。
因此,有两个问题
-
如何在智能指针中获取目标对象的地址?
-
我是否以正确的方式使用智能指针?我应该将
shared_ptr更改为unique_ptr,还是不使用智能指针?
感谢任何其他补充和建议。
【问题讨论】:
-
@selbie 是的,我希望它返回一个指向指针的指针。
标签: c++ linked-list smart-pointers