As explained in the other answers, you segfault because of the recursive implicit destructor. It is possible to fix this without resorting to raw pointers, having to trust the compiler or writing a custom allocator:
~node() {
for (std::unique_ptr<node> current = std::move(next);
current;
current = std::move(current->next));
}
Here you iteratively go through the chain of pointers. This will, one at a time, unchain one pointer and change ownership std::move(current->next)
to current. At the same time the previous unchained pointer, owned by current
, will be released while being overwritten by the move assignment.
You may find the explicit variant more straightforward:
current.reset(current->next.release()));
Is effectively the same as:
current = std::move(current->next));
I prefer the move
version, because it does at no time leave you with a raw pointer. But in that case it does not make a difference.