Littlebitter
Littlebitter

Reputation: 701

Deleting all values from a QMap

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 ?

Upvotes: 14

Views: 17542

Answers (2)

user10609288
user10609288

Reputation:

If both key and value are stored as pointers. You need to execute qDeleteAlltwice for keys and for values. Order doesn't matter. Simple example:

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QHash>

class MyKey
{
public:
    MyKey(int val)
    {
        m_val = val;
        qDebug() << "ClassKey()";
    }
    ~MyKey()
    {
        qDebug() << "~ClassKey() " << m_val;
    }
private:
    int m_val;
};

class MyValue
{
public:
    MyValue(int val)
    {
        m_val = val;
        qDebug() << "ClassValue()";
    }
    ~MyValue()
    {
        qDebug() << "~ClassValue() " << m_val;
    }
private:
    int m_val;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QHash<MyKey *, MyValue *> hash;
    for (int i = 0; i < 10; ++i)
    {
        hash.insert(new MyKey(i), new MyValue(10 + i));
    }
    qDeleteAll(hash.keyBegin(), hash.keyEnd());
    qDeleteAll(hash.begin(), hash.end());
    hash.clear();
    return a.exec();
}

Upvotes: 1

Cutterpillow
Cutterpillow

Reputation: 1777

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.

Upvotes: 31

Related Questions