我的问题是关于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);
}
...
};
当 head = std::move(head->next)
时,会发生三件事情:
- 将
head->next
重置为nullptr
; - 将
head
设置为新值; - 销毁
head
原来指向的 Node 对象。
上述代码之所以能够正常工作,是因为 3 一定会在 1 之后发生,否则链式结构仍然存在。
我想知道是否有书面规定来保证这种顺序,还是这只是一个隐藏的实现细节,这个例子只是偶然能够正常工作。