相关疑难解决方法(0)

移动 unique_ptr:重置源 vs. 销毁旧对象

我的问题是关于https://en.cppreference.com/w/cpp/memory/unique_ptr中的示例

struct List
{
    struct Node
    {
        int data;
        std::unique_ptr<Node> next;
    };
 
    std::unique_ptr<Node> head;
 
    ~List()
    {
        // destroy list nodes sequentially in a loop, the default destructor
        // would have invoked its `next`'s destructor recursively, which would
        // cause stack overflow for sufficiently large lists.
        while (head)
            head = std::move(head->next);
    }
 
    ...
};
Run Code Online (Sandbox Code Playgroud)

当 时head = std::move(head->next),会发生三件事:

  1. 重置head->nextnullptr
  2. 设置head为新值;
  3. head销毁曾经指向的Node 对象;

上面的代码有效意味着 3 保证在 1 之后发生,否则链接仍然存在。

我想知道是否有一个书面规则来保证这样的顺序,或者它只是一个隐藏的实现细节,并且该示例可以正常工作。

c++ move unique-ptr

8
推荐指数
1
解决办法
281
查看次数

标签 统计

c++ ×1

move ×1

unique-ptr ×1