我想使用 QQueue 来存储我的类的对象。该类的成员是指向 QPoint 的指针。我将我的类的对象存储在 QQueue 中并检索它。
#include <QQueue>
#include <QPoint>
#include <QDebug>
class Foo {
public:
Foo(int x, int y);
~Foo();
QPoint bar;
QPoint* baz;
//Q_DISABLE_COPY(Foo) // not sure whether I need this
};
Foo::Foo(int x, int y): bar(x, y) {
baz = new QPoint(x, y);
}
Foo::~Foo() {
delete this->baz;
}
int main(void) {
QQueue<Foo> queue;
Foo a(5, 6);
qDebug() << "a.bar.x()=" << a.bar.x() << ", a.baz->x()=" << a.baz->x();
queue.enqueue(a);
Foo b = queue.dequeue();
qDebug() << "b.bar.x()=" << b.bar.x() << ", b.baz->x()=" << b.baz->x();
return 0;
}
输出:
a.bar.x()= 5 , a.baz->x()= 5
b.bar.x()= 5 , b.baz->x()= 0
09:46:59: The program has unexpectedly finished.
如果我在析构函数中注释掉 delete this->baz;
,我会得到我预期的结果:
a.bar.x()= 5 , a.baz->x()= 5
b.bar.x()= 5 , b.baz->x()= 5
有人能解释一下这是怎么回事吗?在我看来, Foo 的析构函数被提前调用了。谢谢。
最佳答案
Read about "The rule of three/five/zero" .
基本上,默认复制构造函数在您的情况下无效,当您将 Bar
添加到 queue
(按值传递)时使用它。
因此,有两个 Bar
对象,其中 baz
指向相同的 QPoint
。当一个对象死亡时,没有什么不好的事情发生,但是当拷贝死亡时,代码试图释放已经释放的东西。这会导致崩溃。
关于c++ - 如何入队和出队具有 QPoint 指针成员的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55569501/