My question is about the example in 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);
}
...
};
When head = std::move(head->next)
, there are three things happen:
- reset
head->next
tonullptr
; - set
head
to the new value; - destroy the Node object that
head
used to point to;
The above code works means 3 is guaranteed to happen after 1, otherwise the chaining still exists.
I would like to know whether there is a written-down rule to guarantee such order, or it is only a hidden implementation details and the example just works.