我使用gdb来找到与seg错误完全相同的行。它在出队功能中作为注释记录下来。
这是整个队列类。
当队列中有两个对象和标记时,我会在调用dequeue()
时出错。
template <typename T>
void Queue<T>::clear()
{
while(!isEmpty())
dequeue();
}
template <typename T>
void Queue<T>::enqueue(const T& x)
{
if(isEmpty())
{
Queue<T>* temp = new Queue<T>;
m_data = x;
m_next = temp;
return;
}
Queue<T>* temp = this;
while(temp->m_next != NULL)
{
temp = temp->m_next;
}
Queue<T>* node = new Queue<T>();
temp->m_data = x;
node->m_next = temp->m_next;
temp->m_next = node;
return;
}
template <typename T>
void Queue<T>::dequeue()
{
if(isEmpty())
return;
if(m_next != NULL)
{
Queue<T>* temp = m_next;
m_data = temp->m_data;
m_next = temp->m_next;
delete temp; //Seg fault here
}
return;
}
template <typename T>
const T& Queue<T>::front() const throw (int)
{
if(isEmpty())
throw 0;
return m_data;
}
template <typename T>
bool Queue<T>::isEmpty() const
{
return (m_next==NULL);
}
template <typename T>
int Queue<T>::size() const
{
int size = 0;
const Queue<T>* temp = this;
while(temp->m_next != NULL)
{
temp = temp->m_next;
size++;
}
return size;
}
抱歉,以为我已经发布了Queue类:
template <typename T>
class Queue : public AbstractQueue<T> {
public:
Queue(){m_next = NULL;};
virtual void clear();
virtual void enqueue(const T& x);
virtual void dequeue();
virtual const T& front() const throw (int);
virtual bool isEmpty() const;
virtual int size() const;
~Queue(){
clear();
return;
};
private:
T m_data;
Queue* m_next;
};
它继承自此类:
template < typename T >
class AbstractQueue
{
public:
// Purpose: clears the queue
// Postconditions: the queue is now empty
// -- PURE VIRTUAL
virtual void clear() = 0;
// Purpose: enqueue an element into the queue
// Parameters: x is the item to add to the queue
// Postconditions: x is now the element at the end of the queue,
// -- PURE VIRTUAL
virtual void enqueue(const T& x) = 0;
// Purpose: dequeues
// Postconditions: the element formerly at the front of the queue has
// been removed
// Dequeueing from an empty Queue produces no errors, queue remains empty.
// -- PURE VIRTUAL
virtual void dequeue() = 0;
// Purpose: looks at the front of the queue
// Returns: a reference to the element currently in front of the queue
// Exception: if the queue is currently empty, throw SOMETHING!!
// -- PURE VIRTUAL
virtual const T& front() const = 0;
// Purpose: Checks if a queue is empty
// Returns: 'true' if the queue is empty
// 'false' otherwise
// -- PURE VIRTUAL
virtual bool isEmpty() const = 0;
// Purpose: Returns the size of a queue.
// Returns: the number of elements in the Queue
// -- PURE VIRTUAL
virtual int size() const = 0;
// ----------------
// Purpose: Destructor
// -- VIRTUAL
virtual ~AbstractQueue() {};
};
最佳答案
在此代码中:
Queue<T>* temp = m_next;
m_data = m_next->m_data;
m_next = m_next->m_next;
您无需检查m_next是否为非null(如果您位于列表的末尾),因此就可以开始取消引用null指针,并且所有赌注都已关闭。
关于c++ - 删除临时指针时出现段故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15911988/