RAII-style C++ class for linked list Nodes

不羁的心 提交于 2019-12-21 18:13:26

问题


I'm playing with linked lists as an exercise at the moment.

The examples I'm looking at in the Cracking The Coding Interview book have no LinkedList (manager) class, just Nodes, and you hang on to the head Node in your main function.

I looked up C++ implementations, but most seem to be more C-style than C++, i.e. not object-oriented. They use structs, no classes, and have a static method for deleting the list, which you need to explicitly remember to call. I wanted to write a sensible RAII (Resource Acquisition Is Initialization) style C++ class with sensible destructors to handle memory deallocation, and I wanted to use only a Node class (no LinkedList class).

The only way I saw to have this work was to have Node's destructor delete the next Node if there was one, but I've read that this kind of recursive delete is a bad idea, because you end up creating a callstack the same length as the linked list.

So to summarize my question:

  • If writing an object-oriented class to handle linked lists in C++, do you have to have a LinkedList (manager) class which handles the deletion of the list nodes in its destructor?
  • If not, how would you deal with destruction of Nodes?

Thanks!


回答1:


If writing an object-oriented class to handle linked lists in C++, do you have to have a LinkedList (manager) class which handles the deletion of the list nodes in its destructor?

No, the structure is defined by the links between nodes, so there's no need for a separate manager object. It can sometimes be more convenient to have one, especially if you're designing a library like the STL and want all the containers to have a similar interface, but you can certainly implement a linked list with just a node type.

If not, how would you deal with destruction of Nodes?

One way to avoid recursion is to remove each node from the list before deleting it, something like:

~node() {
    while (node * victim = next) {
        next = victim->next;
        victim->next = nullptr;
        delete victim;
    }
}


来源:https://stackoverflow.com/questions/11795035/raii-style-c-class-for-linked-list-nodes

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