views:

439

answers:

4

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

A: 

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.

Xorlev
+2  A: 

From the docs it appears that this is the expected behaviour :

Note that the internal array only ever gets bigger over the life of the list. It never shrinks. The internal array is deallocated by the destructor and by the assignment operator, when one list is assigned to another.

If you want to de-allocate the memory you've got a couple of options

  1. Make sure the destructor is called (using delete {assuming you new'd the list in the first place}, or allowing the QList object to go out of scope)
  2. Assign an empty list to your big list (think this will work)
Glen
But to use delete, wouldn't I need to declare it as pointer QList<int> * memList;?
funny man
@funny man, yes, you would need to allocate it using new
Glen
A: 

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.

Marcus Lindblom
A: 

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.

Jeff Heyob