我有一个队列类,其中我试图动态分配 3 个“样本”对象并将它们放入队列中,然后出列并删除它们。但是示例对象的析构函数:
~Sample() { cout << "Destructing Sample object " << id << "\n"; }
当我尝试将对象放入队列时,由于某种原因被调用。
int main()
{
Sample *samp1;
Sample *samp2;
Sample *samp3;
Queue<Sample> sQa(3);
samp1 = new Sample(1);
samp2 = new Sample(2);
samp3 = new Sample(3);
cout << "Adding 3 Sample objects to queue...\n";
sQa.put(*samp1);
sQa.put(*samp2);
sQa.put(*samp3);
cout << "Dequeing and destroying the objects...\n";
for(int i = 0; i < 3; ++i)
{
delete &sQa.get();
}
return 0;
}
这是输出:
Adding 3 sample objects to queue...
Destructing Sample object 1
Destructing Sample object 2
Destructing Sample object 3
Dequeing and destroying the objects...
Destructing Sample object 1
然后程序崩溃。有谁知道这可能是为什么?此外,如果有必要,这里是 put 函数。(队列类是一个模板)
void put(Qtype data)
{
if(putloc == size)
{
cout << " -- Queue is full.\n";
return;
}
putloc++;
q[putloc] = data;
}