c++ - 如何入队和出队具有 QPoint 指针成员的类?

标签 c++ qt

我想使用 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/

相关文章:

c++ - Qt, C++, 如何退出 QThread

c++ - 用于连接 Qt 5.2.1 (MSVC 2012) 与 OpenCV 的 CMake 选项

c++ - Visual Studio 2012 平台工具集设置不正确

c++ - 这个语法是什么? C++

c++ - 调整动态字符串数组的大小

c++ - Linux 和剪贴板

c++ - 构造/破坏 QApplication 导致 QWebView 搞乱 HTML 的呈现

c++ - 二叉搜索树中序遍历递归函数不能正常工作

c++ - 如何从 QTextEdit 或 QPlainTextEdit 小部件获取当前可见的文本?

qt - QML 中的尺寸是与设备无关的像素吗?