gpt4 book ai didi

c++ - 清理 QList 和 QGraphicsScene 以避免内存泄漏

转载 作者:行者123 更新时间:2023-11-30 03:52:46 24 4
gpt4 key购买 nike

我想彻底清理以避免内存和对象泄漏。

我的误解是 Qt 会自动清除超出范围的对象,除了需要手动删除指针。

在我的代码中,我有一些 QList... 示例:

void someFunction()
{
QList<int> x = QList<int>() << 0 << 0 << 0 << 0;
QList<QImage> y; // filled in some way
QList<QGraphicsScene*> s;

s = otherFunction(x, y);
}

QList<QGraphicsScene*> otherFunction(QList<int>& x, const QList<QImage>& y)
{
QList<QGraphicsScene*> s;
s.push_back(this->scene()); // a few times; of course there is some processing...
return s;
}

void thirdFunction()
{
QList<int> x = QList<int>() << 0 << 0 << 0 << 0;
QList<QImage> y; // filled in some way
QList<QGraphicsScene*> s;

s = otherFunction(x, y);
for (int i = 0; i < s.size(); ++i)
{
view[i]->setScene(s.at(i)); // view is a QList<QGraphicsView*>
}
}

多次调用,我可以看到内存在增加(从任务管理器中看到)。

很明显,当项目超出范围时,它们不会被删除......我立即怀疑场景指针列表。

1) 删除它们的最佳方法是什么?将

qDeleteAll(s);

someFunction() 中就足够了吗?它会删除场景指针,以及场景中的所有 QGraphicItems 吗?还是我需要遍历场景列表并删除所有项目?我必须这样做吗:

    for (int i = 0; i < s.size(); ++i)
{
s.at(i).clear();
} // then
qDeleteAll(s);

2)是否需要删除简单变量列表(intbool)?
对象列表怎么样,比如 QImage

3) 我假设从场景中移除一个项目会删除它的指针。但是现在我读到,从场景中删除一个项目后,需要手动删除它。也是如此

scene().clear();

删除已添加到场景中的QGraphicItem 指针?还是应该使用 delete 调用删除这些项目?

4)thirdFunction 中,我有内存泄漏吗?好像我喜欢!!
我无法删除场景,因为我将它们设置到 View 上...但是已经分配给 View 的场景会发生什么情况?
如何正确清洁它?

最佳答案

1. qDeleteAll使用 C++ 删除容器中的项目 delete运算符(operator)。关于 QGraphicsScene 的 Qt 文档中也有说明。析构函数:

Removes and deletes all items from the scene object before destroying the scene object

所以调用qDeleteAll(s)就足够了.

2.无需删除基本或 Qt 类型列表,如 QList<int>QList<QImage>因为当列表被删除时它们也会被删除。

3. QGraphicsScene::clear()从场景中移除并删除所有项目。所以打电话scene().clear();足够。这相当于调用:

qDeletaAll( scene()->items() );

4.由于 View 不拥有场景的所有权,您应该使用 deleteLater() 删除以前分配的场景。 :

for (int i = 0; i < s.size(); ++i)
{
view[i]->scene()->deleteLater();
view[i]->setScene(s.at(i)); // view is a QList<QGraphicsView*>
}

关于c++ - 清理 QList 和 QGraphicsScene 以避免内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494275/

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