Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unordered_map<std::String, myClass*> - does std::unordered_map::erase() call myClass' DTor?

Tags:

c++

c++11

Assume I have some unordered_map of pointers to class instances, would erasing an object from that map also delete the instance?

(rewording the question:) If I wanted to delete that instance, which version would be right?

if(it != map.end())
{
    delete it->second;
    map.erase(it);
}

or simply

if(it != map.end())
    map.erase(it);

?

UPDATE: as suggested by many people, I moved to using shared_ptr, and it works great!

like image 928
St0fF Avatar asked Oct 21 '14 08:10

St0fF


1 Answers

No, and since this is tagged C++11 you should be using std::unique_ptr / std::shared_ptr to manage your object pointers in the first place, e.g.

std::unordered_map<std::string, std::unique_ptr<myClass>>

Even if you religiously make sure that your pointers are deleted before any call to erase, you still have to consider what would happen in the event of an exception, or if you assign something else to the same key, or any number of other possibilities that might leak. Unless you have a very good reason to use new and delete, don't; stick to std::unique_ptr / std::shared_ptr and std::make_unique / std::make_shared, it's safer and makes your code easier to read.

like image 61
user657267 Avatar answered Sep 21 '22 05:09

user657267