object destruction from heap | linked list using smart pointer | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

object destruction from heap | linked list using smart pointer

Hello I tried to implement linked list using raw pointer as below: https://code.sololearn.com/ca2293A13a14/#cpp Run the code and observe that object destruction is in reverse order of their construction. i.e. first all node class destructor and at last firstly created linked list class destructor This is what we generally expect and I am getting same behavior. Please correct me if something is wrong. Now, refer below code where link list is implemented using smart pointer. https://code.sololearn.com/c551A229A2A1/#cpp Why destructor call is not same as what it is like normal case of first constructed is destroyed last and last constructed first?

16th Feb 2021, 5:14 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 2
Ketan Lalcheta the object does not go invalid *immediately* when the destructor is called. Destructors basically gives you the chance to clean up some mess you made (like deallocating memory to prevent leaks) or to perform some operations. When the destructor call is over, the destroying of the object actually starts. In this process, each member of the object is destroyed by calling their destructors and then doing the same thing on the member objects. After all this is over, the object is no longer valid. Maybe you'll understand with an example. https://code.sololearn.com/W83NKRuoNS3v/?ref=app
16th Feb 2021, 7:07 PM
XXX
XXX - avatar
+ 2
In the first code, you are manually calling `delete` on each pointer, and then displaying the message. In the second code, the destructor on the linked list is called when it is about to be destroyed, which displays the message. Then, the compiler one by one, destroys each member of the linked list class. When it destroys the `head` of the linked list, it calls the destructor, and then proceeds to destroy each member of the node `head`. In this process, it calls the destructor of head->next, which in turn calls the destructor on head->next->next. This continues recursively till each node has been deleted. Note that this is because each node *owns* the next node. If this was not a shared_ptr, but a normal raw pointer, it would have simply deleted the pointer and not the next node.
16th Feb 2021, 5:34 PM
XXX
XXX - avatar
+ 1
Correct... But does it not mean destructor call is over and it suggest that object is no more valid ? Here , it means destructor call done , object no longer exists and then it cares about destroying objects which were created at last (nodes) ?
16th Feb 2021, 6:02 PM
Ketan Lalcheta
Ketan Lalcheta - avatar