Sud*_*ngh 1 c++ pointers unique-ptr
您好,我正在尝试使用指针并学习C++
. 下面是我的代码,我已经注释了 main 函数中的代码行。调试问题但是,我无法这样做。我缺少什么?我的move()
方法不对吗insertNode()
?我得到的错误位于代码下方:
#include<memory>
#include<iostream>
struct node{
int data;
std::unique_ptr<node> next;
};
void print(std::unique_ptr<node>head){
while (head)
std::cout << head->data<<std::endl;
}
std::unique_ptr<node> insertNode(std::unique_ptr<node>head, int value){
node newNode;
newNode.data = value;
//head is empty
if (!head){
return std::make_unique<node>(newNode);
}
else{
//head points to an existing list
newNode.next = move(head->next);
return std::make_unique<node>(newNode);
}
}
auto main() -> int
{
//std::unique_ptr<node>head;
//for (int i = 1; i < 10; i++){
// //head = insertNode(head, i);
//}
}
Run Code Online (Sandbox Code Playgroud)
错误 std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' :尝试引用已删除的函数
除了其他小问题外,主要问题是这一行:
return std::make_unique<node>(newNode);
Run Code Online (Sandbox Code Playgroud)
您正在尝试构造一个指向新节点的唯一指针,并将其传递newNode
给 的复制构造函数node
。但是, 的复制构造函数node
被删除,因为node
包含不可复制类型(即std::unique_ptr<node>
)。
您应该传递 a std::move(newNode)
,但这是有问题的,因为您在堆栈上创建节点,并且它将在函数退出时被销毁。
在我看来,在这里使用 astd::unique_ptr
是一个坏主意,因为,例如,要打印列表(或插入到列表中),您需要std::move
(head
所以您会丢失它)等等。我认为你有一个std::shared_ptr
.