假设,我们有链接列表的以下实现
struct node { node (void) : val(0),next(nullptr) {} int val; std::unique_ptr<node> next; };
我们已按照初步确定了我们的清单
int main (int argc,char* argv[]) { node HEAD; HEAD.val = 0; auto ptr = &HEAD; for (int i = 0; i < 10; ++i) { ptr->val = i; ptr->next.reset(new node); ptr = ptr->next.get(); } ptr->val = 10; ...
现在,我想删除值为1的节点:
ptr = &HEAD; ptr = ptr->next.get(); HEAD.next = std::move(ptr->next);
乍一看,这似乎是明智的.不过,我不确定它是否会导致未定义的行为:
根据http://en.cppreference.com/w/cpp/memory/unique_ptr/operator%3D,
运算符=
Transfers ownership from r to *this as if by calling reset(r.release())
followed by an assignment of get_deleter() from std::forward
(r.get_deleter())
仔细看看unique_ptr :: reset(http://en.cppreference.com/w/cpp/memory/unique_ptr/reset),它会读取
Given current_ptr,the pointer that was managed by *this,performs the
following actions,in this order:
Saves a copy of the current pointer old_ptr = current_ptr
Overwrites the current pointer with the argument current_ptr = ptr
If the old pointer was non-empty,deletes the previously managed object
if(old_ptr != nullptr) get_deleter()(old_ptr)
这意味着在这种情况下,r.get_deleter()的调用将引用一个已被销毁的对象,或者我在这里弄错了?
非常感谢您的回复.
解决方法
我会选择HEAD.next.reset(ptr-> next.release());显式(如果你不关心删除),或HEAD.next = std :: unique_ptr< node>(std :: move(ptr-> next))如果你担心保留删除器.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。