Is it OK to use quot;delete thisquot; to delete the current object?(可以用“删除这个吗?删除当前对象?)
问题描述
我正在编写一个链表,我希望结构的析构函数(一个节点结构)简单地删除自身,并且没有任何副作用.我希望我的列表的析构函数在自身上迭代调用 Node 析构函数(临时存储下一个节点),如下所示:
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();
}
}
所以这将是我的 Node 析构函数:
So this would be my Node destructor:
Node::~Node
{
delete this;
}
这是否可以接受,尤其是在这种情况下?
Is this acceptable, especially in this context?
推荐答案
如果 Node 析构函数正在被调用,那么它已经在被删除的过程中.所以在你的 Node 析构函数中删除是没有意义的.
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.
这也是错误的:
while (temp->next() != NULL)
{
delete temp;
temp = temp->next();
}
相反,您应该将 temp->next() 放入临时变量中.否则,您正在访问已删除的内存.
Instead you should get temp->next() into a temp variable. Otherwise you are accessing deleted memory.
更像这样:
DoublyLinkedList::~DoublyLinkedList
{
Node *temp = first();
while (temp != NULL)
{
Node *temp2 = temp->next();
delete temp;
temp = temp2;
}
}
这篇关于可以用“删除这个"吗?删除当前对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以用“删除这个"吗?删除当前对象?


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01