c++ - How to 'delete' this linked list from memory? -


i've created class building linked list. class declaration follows:

class linkedlist {     private:       int data;       linkedlist *next;       static int count;       public:       linkedlist(void);       ~linkedlist(void);        int insert(int arg);       int remove(int arg);       bool find(int arg); }; 

how can make sure nodes of linked list deleted? destructor made responsible deleting 1 node. used make linked list never thought clearing memory.

the naive implementation

~linkedlist() {delete next;} 

will right thing - delete call destructor on next element, delete 1 following it, , on, delete whole list.

however, means destructors called recursively, deleting long list cause stack overflow. iteration might better:

~linkedlist() {     while (linkedlist * head = next) {         next = head->next;         head->next = nullptr;         delete head;     } } 

as noted in comments, might more appropriate have separate list , node classes, list responsible memory management, , node simple aggregate containing data , link. there's less scope error in destructor, doesn't need nullify pointers prevent recursion:

struct node {     int data;     node * next; };  struct list {     node * head;      ~list() {         while (node * victim = head) {             head = victim->next;             delete victim;         }     } }; 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -