PDA

View Full Version : memory leaks and deleting a QMap



ravas
13th November 2015, 19:46
If we have a QMap<int, Something*>
does deleting the QMap properly clean up the Something*?
"Something" is not part of the object tree.

ChrisW67
13th November 2015, 20:40
Yes, destroying the QMap "properly" cleans up the Someting pointers it owns. That has nothing to with the Something instances those pointers point at, which continue to exist because the container does not own them.

ravas
13th November 2015, 22:48
What is the appropriate loop to deal with the instances?
example:


foreach (Something* thing, a_map)
{
delete thing;
}

d_stranz
13th November 2015, 23:08
More like this:



QList< Something * > things = a_map.values();
foreach( Something * thing, things )
{
delete thing;
}


Edit: although upon reading the docs, it looks like your code would accomplish the same thing. I am more familiar with std:: map<>, where the iterator returns an std:: pair<> containing the key and value.

anda_skoa
14th November 2015, 12:11
Edit: although upon reading the docs, it looks like your code would accomplish the same thing.
Definitely iterating over the map.
Iterating over the values requires two iterations: one for creating the list of values and the the actual loop.

In any case: http://doc.qt.io/qt-5/qtalgorithms.html#qDeleteAll-1

Cheers,
_