实现循环队列时出错?

时间:2012-07-10 03:43:03

标签: c++ queue

我必须为类实现循环队列。当我测试它时,程序正确地排队和出队。但每当我创建一个新对象并将其设置为另一个时,所有内容都会正确打印出来,但最后会崩溃,并出现错误:

Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)

我运行了调试器,它说问题在Dequeue函数中排成一行。这是那个功能。

void CQUEUE::Dequeue()
{
if(Isempty())
{
    cout << "Queue is  empty, nothing to delete." << endl;
    return;
}

if((!Isempty()) && (front == back)) //When there is only 1 item in the queue
{                                   // front and back will point to the same node
    delete front;                   //but it wont be null because of that 1 item
    front = back = 0;   
    return;
}

qnode *p = front;
front = front -> next;
delete p;//<----------DEBUGGER POINTS HERE**************
front -> prev = back;
return;

}

就像我说的,程序运行正常,直到我创建一个新对象并执行此操作

 CQUEUE j = k;//Any Enqueues and Dequeues after this work, but it crashes

这是复制构造函数,这是问题吗?

CQUEUE::CQUEUE(CQUEUE & original)//Will not compile if I put Const 
{                               //in the parameter for some reason
front = back = 0;           //So I took it out
(*this) = original;
front -> prev = back;
back -> next = front;

}

1 个答案:

答案 0 :(得分:1)

在复制构造函数中,执行以下操作:

(*this) = original;

这意味着frontCQUEUE j中的CQUEUE k指针都指向相同的内存。

同时为void CQUEUE::Dequeue()j调用k时,delete p; double 会删除内存,从而导致崩溃。

此外,您的复制构造函数必须声明为constCQUEUE::CQUEUE(const CQUEUE& original)。没有更多的代码很难说,但在你的复制构造函数中,你需要制作指针的深层副本(使用new分配内存)。阅读What is The Rule of Three?可能有所帮助。