Dynamic memory in QList

I do not have much experience with QT, and this problem appeared 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 the first cycle, when I check the memory usage, it rises as new elements are added to memList , but after removing them during the second cycle, the memory usage remains at the same level. I thought the QList was dynamic and it frees up memory when the item is deleted. So either I'm missing something (very likely) or it's not a dynamic structure. Do you have any idea how to make it work?

Hi

+3
source share
5 answers

From the docs , this seems to be the expected behavior:

Note that the internal array only ever grows over the life of the list. He never shrinks. The internal array is freed by the destructor and assignment operator when one list is assigned to another.

If you want to unallocate memory, you have a couple of options

  • Make sure the destructor is called (using delete {assuming you are new to the list first}, or let the QList go out of scope)
  • Assign an empty list to your large list (think this will work)
+4
source

I recall this:

http://cplusplus-soup.com/2010/01/05/freedelete-not-returning-memory-to-os/

It seems that this may be due to memory position / deletion, but I'm not 100% sure about that.

+1
source

The QList is partially between QVector (similar to std :: vector) and QLinkedList (similar to std :: list). QList contains an array of pointers to the objects themselves.

This scheme means that sorting / reordering the list is quick, but the pointer store grows continuously as you add items (like a vector). Thus, removing items from the list frees up the memory used by the items, but not the pointer in the array.

To restore memory, you need to create a new list. QVector has compression (), but it does not look like QList.

0
source

QList is recommended for lists of <1000 objects. If you need to process very large lists and you want the memory to be fixed as objects are deleted, you should consider using QLinkedList.

-1
source

Try this code to free memory from QList

 while( ! memList.isEmpty() ) delete memList.takeFirst(); 
-2
source

Source: https://habr.com/ru/post/1301468/


All Articles