srajeshnkl
srajeshnkl

Reputation: 883

Delete dynamically allocated memory form std::map

I have a map std::map< string,A* > MyMap, here A is a class; its object is created created using "new" and inserted into map like this,

MyMap["first"] = new A();
MyMap["second"] = new A();     // second step
MyMap["third"] = new A();

Like this, I am inserting dynamically created A object into array with in every 5 seconds. After some point I want to release the memory created using "new" I don't want to delete all the items. I want to free up only few items from map. Is it possible only delete the memory taken by particular items? ( For example I want to delete only the space taken for the A object which is created in second step.

Upvotes: 1

Views: 1890

Answers (1)

Ivan Milles
Ivan Milles

Reputation: 314

Definitely. First, obtain a pointer or reference to the object you want to remove. Then, take it out of the map using map.erase(). Now, the object is held only the your pointer or reference, so you can free up its memory using delete.

Upvotes: 1

Related Questions