QT:如何正确清理QSettings以防止内存泄漏?

时间:2015-09-16 20:02:01

标签: c++ qt memory-leaks

我编写了以下小样本测试用例,它只是将一个键/值写入QSettings对象(使用 Qt 5.5 ):

#include <QSettings>

int main()
{
    QSettings settings("/tmp/settings.ini", QSettings::IniFormat);

    std::string data = "world";
    QByteArray arr(data.c_str(), data.size());

    settings.setValue("hello", arr);
    return 0;
}

我编译如下:

$ g++ main.cpp -I${QTDIR}/include -I${QTDIR}/include/QtCore -fpic \
        -L${QTDIR}/lib -Wl,-R -Wl,"$QTDIR/lib" -lQt5Core -o test

运行它不会产生stdout / stderr输出,如预期的那样

$ ./test

但是,通过查看它创建的"settings.ini"文件,我们可以看到它按预期工作:

$ cat /tmp/settings.ini 
[General]
hello=@ByteArray(world)

但是,通过valgrind运行它会报告内存泄漏

$ valgrind --quiet --leak-check=full ./test

==2148== 4 bytes in 1 blocks are definitely lost in loss record 1 of 4
==2148==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2148==    by 0x4EC4CA1: qrand() (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x5012CC3: ??? (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x4FE6291: QFile::open(QFlags<QIODevice::OpenModeFlag>) (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x5013350: QTemporaryFile::open(QFlags<QIODevice::OpenModeFlag>) (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x505CA7D: ??? (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x505DE8C: ??? (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x4FF5A3B: QLockFile::tryLock(int) (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x503DE80: ??? (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x503F0C8: QSettings::~QSettings() (in ${QTDIR}/lib/libQt5Core.so.5.5.0)
==2148==    by 0x400E72: main (in /home/steve/test)
==2148== 

可以看出,这源于QSettings析构函数。

QSettings::sync()

请注意,调用settings.sync()对内存泄漏没有任何影响,它只是将泄漏移到sync()内,而不是析构函数。

这是预期的,因为documentation表示从析构函数中调用sync()

问题:

如何正确清理以防止此内存泄漏?

1 个答案:

答案 0 :(得分:2)

这是一个Qt错误,但你还不知道它是否重要。检查是否可以使更多内存泄漏。在循环中完成整整1000次,如果泄漏1000 int s,你肯定应该提交错误报告。否则它将具有低优先级。

  

如何正确清理以防止此内存泄漏?

您已经正在清理。它是C ++和RAII类,你不应该做任何事情。这不是C。