QList takeLast() and free memory
-
Hi,
Im Building a Programm disired to run for more then 6 Month. Using QList could cause me some Memory Problems as I read about that QList never deletes any Objects.Im Using QList as a kind of Buffer, I "prepend" items and use "takeLast()" to use them and remove them from the list. The size of the list would only be around 10 to 1000, but as any item put in the List would remain in the memory, i could get Problems because the Program runs for quite a long time.
Instead of takeLast(), could i Use this:
@
//QList<Commands> myList does exist with many items.
//Commands is of type enumint mytakeLast()
{
Commands* pi = &myList.last(); //a pointer to the listitem
Commands i = *pi; //make a copie of the listitem, so i can return it later
myList.removeLast(); //remove the item
delete pi; //free memory
return i;
}
@Would this be the right way to prevent me from running out of memory?
Could i also do this with QStringList?Sorry for my english, please use "simple" vocabolary.
-
The standard takeLast() is enough: once you take the pointer, it's your responsibility to delete it. So your mytakeLast() method does not do anything better than the built-in one.
What you do have to deal with is that QList index is always increasing internally. When running for a long time and constantly adding/ deleting stuff, you might hit the ceiling. I thing you need to either use a custom solution, or QQueue, or QVector to be safer. Or use Sean's "QCircularBuffer":https://bugreports.qt-project.org/browse/QTBUG-14262
-
Ok what i want to do is, to take the last item out of the List and send it as a parameter to another function.
Like this:
@
void getLastListItem()
{
anotherFunction(myList.takelast());
}
@As i understood QList so far, in my usage the Item last taken from the List will remain in the memory forever.
Another Question:
Does "void removeLast()" from QVector or QList free the Memory used by the Object stored at the last index? -
Hi,
-
your custom mytakeLast() is wrong. You should not delete a object which doesn't in heap.
-
takeLast() and removeLast() do the nearly same thing. no matter you use QVector, QList or others.
-
If item type is pointer type, It's your obligation to delete them.
If item type is not pointer or is smart pointer, nothing else need to do.
-
-
Hi, The takelast function only decreases the reference count for the object. Since the reference to the object is now your to control, it is your responsibility to release any allocated memory. QList doesn't control it anymore, you do. So when in your anotherFunction you release the memory, no memory leakage occurs. When your anotherFunction only uses the reference, but doesn't deallocate, it will be kept in memory. My advice is to release memory after the anotherFunction().
If like 1+1=2 says your QList consist of pointers that is! When using types, Qt will release the memory automatic when the reference count reaches zero.