是否可以使用“删除此”删除当前对象?

编程入门 行业动态 更新时间:2024-10-25 04:23:23
本文介绍了是否可以使用“删除此”删除当前对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在写一个链表,我想要一个结构的析构函数(一个Node结构体)来简单地删除自己,没有任何副作用。我想要我的列表的析构函数在自身上迭代地调用Node析构函数(暂时存储下一个节点),如下所示:

我的列表类有第一个和最后一个指针 //和我的节点都有一个指向前一个和下一个 //节点 DoublyLinkedList ::〜DoublyLinkedList { Node * temp = first(); while(temp-> next()!= NULL) { delete temp; temp = temp-> next(); } }

所以这将是我的Node析构函数:

Node ::〜Node { delete this;这是可以接受的,特别是在这种情况下吗?

解决方案

如果正在调用Node析构函数,那么它已经在被删除的过程中。所以删除在你的Node析构函数中没有意义。

这也是错误的:

while(temp-> next()!= NULL) { delete temp; temp = temp-> next(); }

而是应该将temp-> next否则,您正在访问已删除的内存。

更像这样:

DoublyLinkedList ::〜DoublyLinkedList { Node * temp = first(); while(temp!= NULL) { Node * temp2 = temp-> next(); delete temp; temp = temp2; } }

I'm writing a linked list and I want a struct's destructor (a Node struct) to simply delete itself, and not have any side effects. I want my list's destructor to iteratively call the Node destructor on itself (storing the next node temporarily), like this:

//my list class has first and last pointers //and my nodes each have a pointer to the previous and next //node DoublyLinkedList::~DoublyLinkedList { Node *temp = first(); while (temp->next() != NULL) { delete temp; temp = temp->next(); } }

So this would be my Node destructor:

Node::~Node { delete this; }

Is this acceptable, especially in this context?

解决方案

If the Node destructor is being called, then it's already in the process of being deleted. So a delete doesn't make sense inside your Node destructor.

Also this is wrong:

while (temp->next() != NULL) { delete temp; temp = temp->next(); }

Instead you should get temp->next() into a temp variable. Otherwise you are accessing deleted memory.

So more like this:

DoublyLinkedList::~DoublyLinkedList { Node *temp = first(); while (temp != NULL) { Node *temp2 = temp->next(); delete temp; temp = temp2; } }

更多推荐

是否可以使用“删除此”删除当前对象?

本文发布于:2023-11-06 01:31:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!