我的模板化队列的 dequeue 函数适用于字符串队列,但如果我使用我的自定义 Robot 类,它会在尝试删除指针时崩溃。我很好奇为什么。
例如,在 main.cpp
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "robotqueue.h"
#include "robotcustomer.h"
#include "servicestation.h"
using namespace std;
int main()
{
//- TEST ONE: QUEUE<STRING> -//
RobotQueue < string > stringQueue;
string a("Tim");
string b("Greg");
stringQueue.enqueue(a);
stringQueue.enqueue(b);
stringQueue.dequeue();
stringQueue.dequeue();
//- TEST TWO: QUEUE<RobotCustomer> -//
RobotQueue < RobotCustomer > robotQueue;
RobotCustomer e("Tim",3);
RobotCustomer f("Greg",5);
robotQueue.enqueue(e);
robotQueue.enqueue(f);
robotQueue.dequeue(); <--- Segfault occurs here
robotQueue.dequeue();
return 0;
}
字符串队列工作正常,但我收到此错误:
***Error in `q': munmap_chunk(): invalid pointer: 0x0000000001d6c108 ***
Aborted (core dumped)
我的模板队列看起来像这样(不知道是否需要更多)。
机器人队列.hpp
// Default Constructor
template <typename T>
RobotQueue<T>::RobotQueue()
{
m_size = 0;
m_front = NULL;
m_back = NULL;
}
// Default destructor
template <typename T>
RobotQueue<T>::~RobotQueue()
{
Node<T>* currNode = m_front, *nextNode = NULL;
while ( currNode != NULL )
{
nextNode = currNode->m_next;
delete currNode;
currNode = nextNode;
}
m_size = 0;
}
template <typename T>
void RobotQueue<T>::enqueue(const T& x)
{
Node<T> *newNode = new Node<T>;
newNode->m_data = x;
newNode->m_next = NULL;
if(m_front == NULL)
m_front = newNode;
else
m_back->m_next = newNode;
m_back = newNode;
m_size++; // Increments queue size
return;
}
template <typename T>
void RobotQueue<T>::dequeue()
{
Node<T>* tempNode = new Node<T>;
if(m_front == NULL)
cout << "dequeue error: Queue is empty" << endl;
else
{
tempNode = m_front;
m_front = m_front->m_next;
delete tempNode; <-- Segfault occurs here in RobotCustomer class
m_size--; // Increments queue size
}
return;
}
我假设它与 RobotCustomer 作为一个类有关,所以 m_data 不能指向它或其他什么?这里不是专家:p
机器人客户.h
/* ------------------ Class RobotCustomer ------------------ */
class RobotCustomer
{
private:
string m_name; // Name of Robot
string* m_reqServices; // Array of services requeseted
int m_numServices; // Number of services requested
int m_currService; // Number of services compelted
bool m_busy; // Logic for if robot is in line/servicing
bool m_done; // Logic for if robot is done
public:
//- functions and such that I don't think affect the queue -//
谢谢你的时间 :)
---------------------UPDATED_WITH CONSTRUCTORS/DECONSTRUCTORS--------------------
机器人客户.cpp
// Default Constructor
RobotCustomer::RobotCustomer()
{
m_name = "";
m_numServices = 0;
m_currService = 0;
m_busy = false;
m_done = false;
}
// Overloaded Constructor
RobotCustomer::RobotCustomer(string n, int x)
{
m_name = n;
m_numServices = x;
m_reqServices = new string[m_numServices];
m_currService = 0;
m_busy = false;
m_done = false;
}
// Default Destructor
RobotCustomer::~RobotCustomer()
{
delete m_reqServices;
}