简体   繁体   English

在C ++中删除链表下一个指针

[英]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... 我理解这可能是一个非常基本的问题,但是如果您在c ++中有一个非常简单的链接列表,例如这样的话...

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的类,那么当您使用运算符new创建这种类型的对象时,就会调用链接的构造函数

link *node = new link;

When you delete an object created with using new then its destructor is called 当您删除使用new创建的对象时,其析构函数将被调用

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. 在您的示例中, next是与link类型相同的对象(指向使用new运算符创建的对象的指针)。 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). 是的,除了,next是私有的,所以不能用任何东西设置(您没有方法或朋友),如果您要具有从链接派生的链接,则析构函数应该是虚拟的,因此正确的代码(而不只是链接) ::〜link由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. Delete调用要删除的析构函数,然后释放内存。 So if you have a linked list (without cycles) and delete the head, it will free the complete list. 因此,如果您有一个链表(无循环)并删除了表头,它将释放整个表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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