c++ - 如何在 C++ 类中删除它(使其不进入无限循环)
问题描述
- 我没有很好地实现一个双向链表,我遇到了内存泄漏的问题。
- 最大的问题是我需要删除我在堆中动态分配内存的节点。
- 每当调用 double_linked_list 类的 remove 函数时,它就会进入无限循环。
- 我尝试调试,但它没有工作。
class double_node{
public:
// Data members
ll data;
double_node * next;
double_node * prev;
// Functions
double_node(){
this->next = nullptr;
this->prev = nullptr;
this->data = LLONG_MIN;
}
double_node(ll data, double_node * next, double_node * prev){
this->data = data;
this->next = next;
this->prev = prev;
}
// WARNING : Memory Leak
// I don't know why defining a destructor gives an error
~double_node(){
cerr << "~double_node() is called\n";
if(this != nullptr){
delete this;
}
}
};
class double_linked_list{
public:
double_node * head = new double_node;
double_node * tail = new double_node;
double_linked_list(){
// Head part
head->data = LLONG_MIN;
head->next = tail;
head->prev = nullptr;
// Tail part
tail->data = LLONG_MIN;
tail->next = nullptr;
tail->prev = head;
}
void append(ll data){
if(head->data == LLONG_MIN){
head->data = data;
}
else if(tail->data == LLONG_MIN){
tail->data = data;
}
else{
double_node * temp = tail;
double_node * last = new double_node;
// Setting up last
last->data = data;
temp->next = last;
last->prev = temp;
last->next = nullptr;
tail = last;
}
}
void remove(ll data){
double_node * temp = head;
while(temp != nullptr and temp->data != data){
temp = temp->next;
}
if(temp->data == data){
double_node * y = temp->prev;
double_node * x = temp;
double_node * z = temp->next;
if (z != nullptr){
z->prev = y;
}
if(y != nullptr){
y->next = z;
}
if(x == head){
head = z;
}
if(temp != nullptr){
x->next = nullptr;
x->prev = nullptr;
delete x;
}
}
}
};
解决方案
如何在 C++ 类中删除它(使其不进入无限循环)
通过不删除this
. 永远不要在析构函数中这样做。而且几乎没有理由在任何功能中这样做。
只需~double_node
完全删除。该节点不拥有任何资源,因此不需要用户定义的析构函数。
我遇到了内存泄漏的问题。
您需要~double_linked_list
在节点上定义循环并删除它们。您还需要遵循5 的规则。
推荐阅读
- ios - 在集合视图单元格中的 UIView 上设置渐变背景
- r - R中的正则表达式将单词与杂乱语音数据中的语音注释进行匹配
- php - 我正在使用 php 通过 PHP 和客户端凭据流连接到 spotify 的 API
- node.js - 如何使用 sequelize-typescript 从源实例创建关联实例
- r - 任何人都可以帮助解释两个站点之间物种组成的 ANOSIM 结果吗?
- python - 当 if-else 块的两个子句中都存在赋值时,为什么没有为变量赋值?
- python-3.x - 加速熊猫 series.rolling.appy()
- android - 如何使用单条字符和单线生成组合图
- html - 按指定尺寸搜索图片
- linux - 如何使用 wget 访问两个网站,但将第一个网站的输出发送到`/dev/null`?