如何释放QByteArray.append()分配的内存(重新)

时间:2018-08-14 13:26:45

标签: qt qbytearray

如何释放由QByteArray中append()重新分配的内存?

我在C ++头文件中定义了一个QByteArray:

QByteArray buffer;

,然后在cpp文件中初始化如下内容:

Root:Root():
    buffer(QByteArray())
{
}

Root:Append(const QByteArray &chunk)
{
    buffer.append(chunk);
}

Root:Test()
{
    // Make the number bigger if 3000 is not big enough for 
    // append() to trigger reallocate memory
    for (int i = 0; i < 3000; i++){
        Append("xxxxxxxxxxxxxx");
    }
    // Private Bytes and Working set get increased

    buffer.clear();
    // Private Bytes and Working set DOES NOT get decreased
    // How to release the memory (re-)allocated by append() 
    // in QByteArray ??
}

1 个答案:

答案 0 :(得分:2)

下面将把新的空QByteArray移到旧的QByteArray中,从而有效释放分配的所有内存:

myQByteArray = QByteArray();

感谢assignment运算符:

QByteArray &QByteArray::operator=(QByteArray &&other)

将其他对象移动到此QByteArray实例。 Qt 5.2中引入了此功能。