dynamic memory in QList

青春壹個敷衍的年華 提交于 2019-12-04 15:21:53

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)

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.

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.

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.

Krishna Prasad

Try this code to free memory from QList

while( ! memList.isEmpty() )
    delete memList.takeFirst();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!