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 ?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top