Is a recursive destructor for linked list, tree, etc. bad?

非 Y 不嫁゛ 提交于 2019-12-01 16:06:30

There will be a stack memory consumption issue if you do this for linked lists. Destroying such a linked list will cause recursive d'tor of your Node, whereas the recursion depth will grow linearly with the size of your linked list.

Just do the experiment: enter several millions of nodes into your list and then destroy it. I bet you'll get the stack overflow (unless you configured your thread to reserve enormous stack size). Especially in debug build you'll run out-of-stack very early.

OTOH doing this for trees is ok, at least from technical perspective. Tree cleanup is usually implemented recursively anyway, the even fact if the above recursive function belongs to the tree or to the Node is not important.

The recursion depth of destroying the tree will grow logarithmically with the tree depth, which is ok.

Think of ownerships of the linked item.

Does it make sense that a Node object owns it next kin? It surely makes sense that a Node owns the attached satellite data, so you should cleanup this when the Node is being destroyed.

The LinkedList owns its nodes, so it should be responsible to destroy them properly without any in-memory-leftovers.

The LinkedList object should be able to add and remove nodes, so from the ownership point of view it is responsible to cleanup them for example by removing every node in the list iteratively.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!