【发布时间】:2016-10-16 02:56:39
【问题描述】:
这是我第一次在此处实际发布问题!我在为单链表创建复制构造函数时遇到了一些麻烦。我在这个网站和其他各种网站上搜索了一个可比较的例子,但无济于事。我试图使用智能指针,到目前为止只使用了unique_ptr(s)。此函数旨在对其传递的链表进行深层复制。到目前为止,我已经尝试了以下方法,但我只得到了一个段错误。我已经进行了一些测试,我相信我的 insert_front() 和 insert_back() 函数运行良好。如果有帮助的话,我确实有指向头部和尾部的指针。以下是我试过的代码。
Deque::Deque(const Deque& deque2copy){
this -> head = 0;
unique_ptr<Node> temp = make_unique<Node>(deque2copy.head -> val, move(deque2copy.head->next));
while(temp != 0){
this ->insert_back(temp->val);
temp = move(temp-> next);
}
}
更新 #1
Deque::Deque(const Deque& deque2copy){
if(deque2copy.head->next == nullptr){
return;
} else {
this -> head = 0;
unique_ptr<Node> temp = make_unique<Node>(*deque2copy.head->next);
while(temp != 0){
this ->insert_back(temp->val);
temp = move(temp-> next);
}
}
}
【问题讨论】:
-
为什么要从被复制的容器中移出?那是
auto_ptr不直观 -
没有
move()它似乎无法编译。我认为需要允许复制unique_ptr? -
Move 可以从中移动。如果你搬家,你就不再得到原件了。我想你可能想要
make_unique<Node>(*deque2copy.head->next) -
我现在只要调用复制构造函数就会出现段错误:/
-
啊,那么只有当指针
deque2copy.head->next不为空时才构造一个副本
标签: c++ linked-list copy-constructor smart-pointers deque