gpt4 book ai didi

c++ - QListWidget内存泄漏

转载 作者:太空宇宙 更新时间:2023-11-04 13:29:03 24 4
gpt4 key购买 nike

所以我有这个方法:

void SomeClass::SomeMethod() {
QString information;
QListWidgetItem *dataline = new QListWidgetItem();

information = "stuff & more stuff";

dataline->setText(information);
dataline->setFont(QFont("Monospace"));
dataline->setStuff(moreStuff::things);

//! listData is a pointer to QListWidget object.
ui.listData->insertItem(ui.listData.count(), dataline);
} //! Boom, memory leak!

在 Qt 文档中它是这样说的:

If you need to insert a new item into the list at a particular position, then it should be constructed without a parent widget. The insertItem() function should then be used to place it within the list. The list widget will take ownership of the item.

但是每次调用该方法时,VLD(可视化泄漏检测器)都会检测到内存泄漏。

1) VLD 实际上是正确的,并且存在内存泄漏?

2) 还有其他方法可以解决这个问题吗? (我尝试不对 dataline 对象进行堆分配,并将其地址传递给 insertItem 方法,但似乎不起作用。

编辑:这是包含 ui 对象的类:

#include "ui_Validator.h"

class Validator: public QMainWindow {
Q_OBJECT
public:
Validator(QWidget *parent = 0);
~Validator();
public slots:
void stuff1();
void stuff2();
void stuff3();
void stuff4(const QString &data);
void stuff5(const Rats &data);
signals:
void startGeneratingSignal(Cat param);
void stopGeneratingSignal(Dog param);
void initStuff();
void configStuff(Rats param);
void stopThreadIOloop();
private:
Ui::Validator ui; //! This object is from Qt-generated ui_Validator.h.
SomeThreadObj *objActivity;
QThread *objActivity;
SomeInterface interface;
};

以及来自 cpp 文件的析构函数:

Validator::~Validator() {
//! EDIT: It's ok, when this destructor is called, it means that all the application is closed, so there is no need for explicit cleanup, the OS will take care of that.
ui.listData->clear();
emit killIOloop();
qDebug() << "~Validator";
}

因此,如您所见,ui 对象是在程序启动时(主窗口)第一次构造的,并在调用析构函数时超出范围(当我退出应用程序时)(出于某些原因,我有意不删除 objActivityobjActivity)。

最佳答案

我已经用 VLD 和下面的代码写了一个简单的例子:

test1::test1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QString information;
QListWidgetItem *dataline = new QListWidgetItem();

information = "stuff & more stuff";

//Dataline dataline = new Dataline();
dataline->setText("test");
dataline->setFont(QFont("Monospace"));


//! listData is a pointer to QListWidget object.
ui.listData->insertItem(ui.listData->count(), dataline);
}

test1::~test1()
{

}

MainWindow 关闭后,QListModel Destructor 被调用,并在一个明确的方法中删除ListWidget 的所有项。

VLD 的输出:

No memory leaks detected.
Visual Leak Detector is now exiting.

如果您显式调用 ListWidget 的 clear 方法:相同的输出。

关于c++ - QListWidget内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32243218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com