I have a Qlist full of objects created dynamically. Prior to terminating my program, I call myqlist.clear()
My question is: does this also delete (free) the objects which are contained in the list? Valgrind is giving me some lost blocks and I'm wondering if I misunderstood how the qlist clear method works.
Or, do I need to iterate through the qlist and delete each object?
Update: I can confirm that mylist.erase(iterator) is removing the item from the list, but NOT freeing the dynamically allocated object. (The object is a dynamically instantiated class). Very strange! I switched from Qlist to QLinkedList but same results. Remember, my QLinkedList is a QLinkedList< myclass> not a QLinkedList<*myclass>
Here's the actual code in case someone can find what I'm doing wrong:
// Here I define a couple important items. Note that AMISendMessageFormat is a class
typedef QLinkedList<AMISendMessageFormat> TSentMessageQueue;
TSentMessageQueue m_sentMessageQueue;
// Here I create the message and append to my QLinkedList
AMISendMessageFormat *newMessage = new AMISendMessageFormat(messageToSend);
m_sentMessageQueue.append(*newMessage);
// Here I delete
for (TSentMessageQueue::Iterator sMessagePtr = m_sentMessageQueue.begin(); sMessagePtr != m_sentMessageQueue.end(); )
{
sMessagePtr = m_sentMessageQueue.erase(sMessagePtr);
qDebug() << "Sent size after erase: " << m_sentMessageQueue.size(); // Confirmed linked list is shrinking in size
}
And after iterating through the list and erasing, valgrind shows each of the AMISendMessageFormat objects are lost blocks!
I suspect this has something to do with erasing inside a loop with an iterator...but I can't get my head around this!
See detailed solution below...problem was that the append function makes a copy and adds it to the list...I though it was adding the actual object (not a copy)...so the problem was the 'new' copy was being leaked.
QList
so you don't have to deal explicitely with that. It also makes more explicit who has ownership of those objects. – YirinecQList
takes ownership of pointers and I believe Qt has aQSharedPointer
so I'm not sure how this does not apply. Am I missing something here ? – Yirinecappend
to take it. It has no knowledge whatsoever that there's a pointer involved. You dereference the pointer beforeappend
gets to see it. You must also learn not to allocate things on the heap for no good reason. If it fits on the stack, use the stack. – Garrote