简体   繁体   中英

Deleting a linked list next pointer in c++

I understand this probably a very basic question but nevertheless if you have a really simple linked list in c++ something like this...

class link{
    link * next;
    ~link(void){
         delete next;
    }

}

If the destructor is called on the head of this linked list and its pointer to the next node is deleted does the destructor of the next node get called? Effectively would calling the destructor on the head deleted all the links in the list. Or would the rest of the list just hang there?

Yes, object's destructor will be called when you delete it. Therefore, in this implementation all nodes (or links, if you prefer) after a deleted node will be also destroyed.

It is all simple. If you have a class for example link then when you create an object of this type using operator new then a constrauctor of link is called

link *node = new link;

When you delete an object created with using new then its destructor is called

delete node;

In your example next is the same object of type link (pointer to object created with operator new) as the object that holds it. So its destructor will be called when operaor delete is applied to it.

yes, except, that next is private so can never be set by anything (you have no methods or friends) and if you are going to have links that derive from link the the destructor should be virtual so the correct code (rather than just link::~link is called by delete). you DO need to delete next because it is a pointer to an instance of an object. without the delete then nothing would happen (the destructor of a pointer does not delete the object it pointer to).

Delete calls the destructor of the to-be-deleted and frees the memory afterwards. So if you have a linked list (without cycles) and delete the head, it will free the complete list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM