假设,我们有链接列表的以下实现
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()的调用将引用一个已被销毁的对象,或者我在这里弄错了?
非常感谢您的回复.