Deleting all values from a QMap

Littlebitter picture Littlebitter · Apr 6, 2013 · Viewed 13.9k times · Source

I have a QMap consist of pointers to class objects, allocated using new. I need to delete all these pointers. What is the proper way of doing this with QMap ? I can do it this way:

QList<ClassName*> allVals = map.values();
for (QList<ClassName*>::iterator it = allVals.begin(), endIt = allVals.end(); it != endIt; ++it) {
    delete *it;
}

But is there a better way of doing the same ?

Answer

Cutterpillow picture Cutterpillow · Apr 6, 2013

The best way to do this is to use qDeleteAll(...):

qDeleteAll( map );  //  deletes all the values stored in "map"
map.clear();        //  removes all items from the map

qDeleteAll(...) can be used on all of Qt's containers. This way you don't need to worry about a loop nor worry about deleting items individually.