我正在尝试使用链表的概念创建一个 List 类,虽然我最初使用的是 C++ 标准 new
关键字,但我决定将其切换为 C++11 std::shared_ptr
。但是,当使用智能指针时,我无法让程序正常运行,因为它崩溃了。以下是更改前的一些代码:
class List
{
public:
void push_back(...) {
Node *temp = new Node;
...
if (!head) {
head = temp;
return;
}
else {
Node *last = head;
...
last->next = temp;
}
}
...
private:
Node *head = nullptr;
};
下面是变化后的样子:
class List
{
public:
void push_back(...) {
std::shared_ptr<Node> temp(new Node);
...
if (!head) {
head = temp.get();
return;
}
else {
Node *last = head;
...
last->next = temp.get();
}
}
...
private:
Node *head = nullptr; // don't need this to be a smart ptr
};
我觉得问题可能在于 head
和 last
不是动态分配的,也许它们需要使用 shared_ptr
,但我不确定。我到底做错了什么,我该如何解决?我真的希望这不是重复的,因为我似乎找不到任何可以解决我的问题的方法。谢谢。
编辑:
这是 Node
结构:
struct Node{
int data;
Node* next;
};
最佳答案
首先要有 std::shared_ptr
的原因是让 std::shared_ptr
完全和完全拥有指针,并使其 std::shared_ptr
有责任在对指针的最后一次引用消失后删除
它。这就是 std::shared_ptr
的意义所在。
这意味着一旦将指针放入 std::shared_ptr
中,std::shared_ptr
现在将完全负责管理指针。它完全拥有它。
因此,将指针放入 std::shared_ptr
中是没有意义的……然后立即将其取出:
head = temp.get();
get()
函数存在的原因有很多,但这不是原因之一。
为了正确使用std::shared_ptr
,一切都必须是std::shared_ptr
。 head
需要是一个 std::shared_ptr
:
std::shared_ptr<Node> head; // yes, it does need to be a smart ptr
为什么它需要是一个std::shared_ptr
?好吧,如果不是,您认为在这种情况下会发生什么:
std::shared_ptr<Node> temp(new Node);
具体来说,当这个 temp
智能指针被销毁时,这个函数什么时候返回?好吧,因为它将是最后一个引用此 Node
的 std::shared_ptr
,它会很高兴地 delete
它。您之前get()
它并将其放入head
的事实并不重要。所以现在你有一个 head
指向一个 delete
d 节点。随之而来的是欢闹。
这就是为什么一切都必须是 std::shared_ptr
的原因。不仅是 head
,Node
的 next
成员也 also 需要还有一个 std::shared_ptr
。
现在,有一个涉及循环引用的陷阱,它在 std::shared_ptr
进入画面时发挥作用。但这将是一个不同的问题。
关于C++ 设置指针等于 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38364773/