Reputation: 599
My question concern memory management.
I got this container :
typedef hash_map<const string, Powerdomain*, strptrhash, strptrequal> PowerdomainHashMap;
now I add one element in it
PowerdomainHashMap powerdomainMap;
Powerdomain* pd1=new Powerdomain("Powerdomain1");
powerdomainMap.insert(Powerdomain_pair(pd1->getName(),pd1));
After that my program does a first step.
Now that the first step is done, i no longer need the powerdomains and want to delete them.
Is a powerdomainMap.clear()
sufficient ? Will it destroy all the value entries in the map (ie call delete on every Powerdomain* in the map?
(I think it is better than calling delete on a iterator on the map but i am not sure)
Upvotes: 1
Views: 1647
Reputation: 545618
Is a
powerdomainMap.clear()
sufficient ?
No. You have manually acquired memory (using new
), you need to manually release it (using delete
). Better to use smart pointers instead of raw pointers though (preferably std::shared_ptr
).
Upvotes: 3
Reputation:
No it won't - you need to iterate over the map and call delete on the contents yourself. Or better yet, use a map of smart pointers which will do the delete for you. Another alternative, if you don't need polymorphism, is to use a map of name to values, not pointers, in which case you can lose the dynamic memory management stuff altogether.
Upvotes: 5