I'm trying to learn about C++ and I am having issues with memory management and the concept of destructors. I have tried to write a Queue implementation using Linked Lists, and I am receiving "Aborted (Core Dumped)" error messages when I try to delete my linked list nodes in my destructor method (bolded). If anyone knows what I'm doing wrong please let me know!
Here's the code for my destructor method:
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;
}
}
And for reference here's my full linkedlist queue implementation:
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;
}
}
EDIT:
I've also tried the following definition for the destructor but I am getting the same error:
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;
}
}
Aucun commentaire:
Enregistrer un commentaire