【发布时间】:2020-05-27 11:24:10
【问题描述】:
我编写了一个基于链表的队列,其中每个节点都链接到队列中它后面的节点。程序中的所有其他功能都可以正常工作。出于某种原因,这个析构函数给了我一些问题,我不知道为什么。
我收到此错误:
抛出异常:读取访问冲突。 温度为 0xCDCDCDCD。
感谢您提供的任何帮助。
#pragma once
#include <iostream>
#include "Node.h"
template <typename T>
class LQueue
{
Node<T>* front;
Node<T>* end;
int length;
public:
LQueue();
~LQueue();
//Add item into queue
void enqueue(T x);
//Remove item from front of queue
void dequeue();
//return item at front of queue
T peek();
//Is queue empty?
bool isEmpty();
int getLength() { return length; }
};
template<typename T>
inline LQueue<T>::LQueue()
{
front = nullptr;
end = nullptr;
length = 0;
}
template<typename T>
inline void LQueue<T>::enqueue(T x)
{
Node<T>* temp = new Node<T>;
temp->data = x;
length++;
if (isEmpty())
{
temp->next = nullptr;
front = temp;
end = temp;
}
else
{
end->next = temp;
end = temp;
}
}
template<typename T>
inline void LQueue<T>::dequeue()
{
if (isEmpty())
{
std::cout << "\n[!] Empty Queue, Nothing To Remove.\n";
return;
}
if (end == front)
{
delete front;
front = nullptr;
end = nullptr;
}
else
{
Node<T>* temp = front->next;
delete front;
front = temp;
}
length--;
}
template<typename T>
inline T LQueue<T>::peek()
{
return front->data;
}
template<typename T>
inline bool LQueue<T>::isEmpty()
{
if (front == nullptr)
return true;
else
return false;
}
template<typename T>
inline LQueue<T>::~LQueue()
{
Node<T>* temp = front;
while (temp != nullptr)
{
Node<T>* temp2 = temp;
temp = temp->next;
delete temp2;
}
}
【问题讨论】:
-
front似乎没有初始化。一些编译器使用0xCDCDCDCD作为调试版本中未初始化变量的初始值。 -
0xCDCDCDCD是未初始化堆内存的常见 Visual Studio 调试器值。您似乎忘记在某个地方的构造函数中初始化一些成员变量。 -
我添加了整个班级 @pts ,而且我相信我确实相信我初始化了前面
-
front已初始化,但end->next不会为每个长度超过 1 的列表初始化(除非Node<T>自行处理)。 -
A minimal reproducible example 应该能够重现该问题。提供的代码不完整。