【发布时间】:2012-02-24 23:06:31
【问题描述】:
为什么进入复制构造函数会崩溃?
在您将在我的类定义中找到的复制过程中,我确保将作为其他原始队列的副本创建的队列在开始复制之前为空:假设队列 q1 不为空并且我想把q1变成q2。我想在将q2的内容复制到q1之前清空q1的内容..
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
class Dnode
{
public:
Dnode(int);
int n;
Dnode* l, *r;
};
Dnode::Dnode(int tx)
{
n = tx;
l = r = NULL;
}
class Queue // reminder: insertions at the rear, deletions at the front
{
public:
Queue();
void enqueue(int x);
int dequeue(void);
bool empty(void) const;
void display(void) const;
Queue(const Queue&); //copy constructor
private:
Dnode* front, *back;
void copy(Dnode*);
void free();
};
Queue::Queue()
{
front = back = NULL;
}
void Queue::enqueue(int x)
{
Dnode* d = new Dnode(x);
if (empty())
front = back = d;
else
{
back->r = d;
d->l = back;
back = d;
}
}
int Queue::dequeue(void)
{
assert(! empty());
Dnode* temp = front;
front = front->r;
if (front == NULL)
back = NULL;
else front->l = NULL;
int x = temp->n;
delete temp;
return x;
}
bool Queue::empty(void) const
{
return front == NULL;
}
void Queue::display(void) const
{
for (Dnode* d = front; d != NULL; d = d->r)
cout << d->n << " ";
cout << endl;
}
void Queue::copy(Dnode* dn) // "dn" will be "Front" of Queue being copied
{ // this procedure will be called in Copy Constructor
Dnode* temp=front; // found underneath this procedure
while(front!=back)
{
front=front->r;
delete temp;
temp=front;
}
delete temp;
front=back=temp=NULL;
if(dn!=NULL)
{
while(dn->r!=NULL)
{
enqueue(dn->n);
dn=dn->r;
}
enqueue(dn->n);
}
}
Queue::Queue(const Queue& x)
{
copy(x.front);
}
int main()
{
Queue q;
if (q.empty()) cout << "q empty" << endl;
for (int i = 0; i < 10; i++) q.enqueue(i);
q.display();
int x = q.dequeue();
cout << "x is " << x << endl;
q.display();
Queue q1(q); //<----program crashes when we get here
q1.display();
}
【问题讨论】:
-
复制时为什么要删除?复制期间无需释放内存。实际上,您应该在 Queue 的新实例中分配内存来保存副本。
-
你到处使用和删除未初始化的指针...
-
如您所说,清空将成为其他队列副本的队列可能是不必要的,但这不应该是程序崩溃的原因吗?我做错了什么?
标签: c++ class constructor copy