我试图了解C ++,我遇到了内存管理和析构函数概念的问题。我曾尝试使用链接列表编写一个Queue实现,我正在接收" Aborted(Core Dumped)"我尝试在析构函数方法中删除链表节点时出现错误消息(粗体)。如果有人知道我做错了什么,请告诉我!
这是我的析构函数方法的代码:
template <class T>
Queue<T>::~Queue(){
Node<T> *currHead = head;
while(currHead != NULL){
Node<T> *nextHead = currHead->next;
delete currHead;
currHead = nextHead;
}
Node<T> *currTail = tail;
while(currTail != NULL){
Node<T> *nextTail = currTail->next;
delete currTail;
currTail = nextTail;
}
}
此处参考我的完整链表列表实现:
template <class T>
class Node{
public:
T data;
Node<T> *next=NULL;
};
template <class T>
class Queue{
public:
Queue();
~Queue();
void push(T);
T pop();
int size=0;
Node<T> *head=NULL;
Node<T> *tail=NULL;
};
template <class T>
Queue<T>::Queue(){}
template <class T>
Queue<T>::~Queue(){
Node<T> *currHead = head;
while(currHead != NULL){
Node<T> *nextHead = currHead->next;
delete currHead;
currHead = nextHead;
}
Node<T> *currTail = tail;
while(currTail != NULL){
Node<T> *nextTail = currTail->next;
delete currTail;
currTail = nextTail;
}
}
template <class T>
void Queue<T>::push(T data){
Node<T> *node = new Node<T>;
node->data = data;
if(head == NULL){
head = node;
}else{
tail->next = node;
}
tail = node;
size++;
}
template <class T>
T Queue<T>::pop(){
if(size == 0){
throw "Empty Queue";
}else{
Node<T> *oldHead = head;
T oldData = oldHead->data;
head = head->next;
size--;
delete oldHead;
return oldData;
}
}
编辑:
我还尝试了以下析构函数的定义,但我得到了同样的错误:
template <class T>
Queue<T>::~Queue(){
while(head != NULL){
Node<T> *currHead = head;
head = head->next;
delete currHead;
}
while(tail != NULL){
Node<T> *currTail = tail;
tail = tail->next;
delete currTail;
}
}
答案 0 :(得分:3)
在析构函数的第一部分中,您将删除从head开始的所有列表项。在析构函数的第二部分中,您尝试使用尾部保留的指针再次删除最后一个列表项,但它已在第一部分中删除。
答案 1 :(得分:0)
删除指针不会更改指针或指向已删除内存的任何其他指针:
#include <iostream>
int main() {
int* head = new int[4];
int* tail = head;
delete head;
std::cout << "head = " << (void*)head << ", tail = " << (void*)tail << "\n";
}
您的代码应该是:
template<typename T>
Queue<T>::~Queue(){
Node<T> *currHead = head;
while(currHead != nullptr){
Node<T> *nextHead = currHead->next;
delete currHead;
currHead = nextHead;
}
head = tail = nullptr;
size = 0;
}
或者你的pop功能是否有效:
template<typename T>
Queue<T>::~Queue() {
while (size)
pop();
}