5

I've got a QMap with the QString key and with value pointer to an Object of myclass. But I don't know how to delete a pointer from QMap when I allocate the value of QMap dynamically:

QMap<QString, myClass*> types;

myClass *type = types.value(typeKey);
    if (!type) {
        type = new myClass;
        types.insert(typeKey, type);

How shall I delete a pointer by a key? I'm aware of QMap methods like remove. Is that safe to use?

What about the following:

const QString key = types.key(static_cast<myClass*>());
    types.remove(key);
elgolondrino
  • 665
  • 9
  • 33

2 Answers2

11

The remove() function removes the item from the map, however it does not delete it, so you have to do it yourself, if it is a pointer to the object. I would do that in the following way:

myClass *type = types.take("foo");
delete type;
vahancho
  • 20,808
  • 3
  • 47
  • 55
5

As QMap::clear doesn't delete pointers, there is another way of doing it with qDeleteAll function. qDeleteAll works on values only in case of QMap and QHash and not on keys even those are of pointer type, so below example will work only on values of kay-value container. In this value must be of pointer type.

QMap<int,Employee *> mlist;
mlist.insert(1,new Employee("Blackpool", "Stephen"));
mlist.insert(2,new Employee("Twist", "Oliver"));

qDeleteAll(mlist);
#or you can do it like
qDeleteAll(mlist.begin(),mlist.end());

update: and yes always use clear() after it, to remove the entries from maps e.g. mlist.clear();

Sachin Nale
  • 139
  • 2
  • 4