I don't have much experience with QT and this problem came out today.
QList<int> memList;
const int large = 100000;
getchar();
for (int i=0; i<large; i++)
{
memList.append(i);
}
cout << memList.size() << endl;
getchar();
for (int i=0; i<large; i++)
{
memList.removeLast();
}
cout << memList.size() << endl;
getchar();
After first loop when I check memory usage it goes up as new elements are appended to the memList
but after removing them within second loop the memory usage stays at the same level. I thought that QList
was dynamic and it would free memory when element is removed. So either I'm missing something (very probable) or it is not dynamic structure. Do you have any ideas how to make it work?
Regards
QList is recommended for lists of < 1000 objects. If you need to handle very large lists and need the memory to be reclaimed as objects are deleted, you should consider using QLinkedList.
QList is partway between QVector (similar to std::vector) and QLinkedList (similar to std::list). QList holds an array of pointers to the objects themselves.
This scheme means that sorting/reordering the list is fast, but the pointer-store grows continuously as items are added (similar to a vector). Thus, removing items from the list frees the memory used by the items, but not the pointer in the array.
To reclaim memory, you need to construct a new list. QVector has squeeze() but that doesn't seem present in QList.
Try this code to free memory from QList
I recall reading about this:
http://cplusplus-soup.com/2010/01/05/freedelete-not-returning-memory-to-os/
It seems it may be to do with memory allocation/deletion behavior, but I'm not 100% sure about that.
From the docs it appears that this is the expected behaviour :
If you want to de-allocate the memory you've got a couple of options