PDA

View Full Version : Proper way to delete a QMap



jano_alex_es
16th June 2009, 10:23
Hi, I have a QMap filled with pointers to objects, and I'd like to ask what's the proper way to delete them.

I planned to loop though the map and delete the items one by one... but I saw the "clear()" method.

void QMap::clear ()
Removes all items from the map.

Does it means "clear()" will delete dynamic objects and free the memory?

thanks!

spirit
16th June 2009, 10:24
have a look at qDeleteAll.
QMap::clear doesn't delete pointers.

jano_alex_es
16th June 2009, 10:26
that's it.

thanks!

sachinsnale
28th February 2020, 12:58
Things which should be taken care when using QDeleteAll with QMap
clear() will only clear the pointers, it will not delete the memory associated with it.
QDeleteAll will work on the value part of the QMap.
e.g QMap<QString, SomeClass*> mymap;
so when you do QDeleteAll on 'mymap' it will delete value part.
if you have thing like
e.g QMap<SomeClass*, SomeClass*> extendedMap;
as QDeleteAll only deletes value part and not the keys.
you have to specifically delete keys as well.

and then call clear() on it so that it will not have dangling pointers

d_stranz
28th February 2020, 17:31
e.g QMap<SomeClass*, SomeClass*> extendedMap;

as QDeleteAll only deletes value part and not the keys. you have to specifically delete keys as well and then call clear() on it so that it will not have dangling pointers

BUT, if you are using this map to associate pointers to instances of the same class and it is a two-way map (i.e. the same pointer appears as both a key -and- a value), then you do not want to delete both the keys and the values, because then you will be double-deleting everything. Only if it is a one-way map where keys and values are pointers which appear only on one side do you want to delete both.

IMO, the easiest (and safest) way to store pointers in a QMap (or std:: map, or really any collection data structure) and guarantee that the object instances they point to will be deleted when the map is cleared is to use smart pointers, for example QSharedPointer or std:: shared_ptr. By using shared pointers, you create the object, wrap it in a shared pointer, and forget about its lifetime. No memory leaks because you called clear() instead of deleteAll(), because with smart pointers clear() has the same effect as deleteAll(). And especially if you are storing pointers in both a collection and in some other data structure, using a smart pointer will guarantee that you won't accidentally delete a pointer and leave a dangling reference somewhere else.