I was going through this blog post and came across this code.
#include <iostream>
#include <string>
using namespace std;
struct LNode {
int data;
LNode* next;
LNode(int n){data = n; next = NULL;}
void add_to_end(int n) {
if (next)
next->add_to_end(n);
else
next = new LNode(n);
}
~LNode() { cout << " I am from LNode Destructor " << endl; delete next; }
};
int main()
{
LNode root(1);
root.add_to_end(2);
root.add_to_end(3);
root.add_to_end(4);
}
The output of this code is
I am from LNode Destructor
I am from LNode Destructor
I am from LNode Destructor
I am from LNode Destructor
For some reason I always thought I had to traverse through the linked list using some kind of while or for loop and go on deleting all the nodes that I had dynamically allocated using new. But in above code how did the destructor got called four times and how did it automatically traverse through the linked list creating this domino effect (completely deleting the allocated memory by itself ).
Aucun commentaire:
Enregistrer un commentaire