Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `unordered_map::erase()` always call the destructor immediately?

Say I have std::unordered_map<int, Foo> myMap;. If I call myMap.erase(1);, will Foo's destructor always be called immediately? Or is the standard library allowed to hang on that instance of Foo for as long as it wants, and maybe reuse it later?

(I understand that everything will always be properly destructed in the end, when the map itself is destroyed.)

like image 945
gregschlom Avatar asked Aug 31 '25 01:08

gregschlom


1 Answers

I went over https://eel.is/c++draft/#containers, and it appears that it's not actually required. Destroying the map, and copy or move into a container require that elements be destroyed, but the only mutating method I see that explicitly requires destruction is pop_back and pop_front.

Theoretically, it appears that a map could contain an internal cache of "freed" nodes to reuse for future inserts, and it appears that it's not actually required to destroy and recreate the data itself if it does this. At least until the map destructor is called.

This is probably an oversight in the C++ spec, and I would be shocked if anyone implemented a map that didn't destroy and recreate the data though, even if they do cache nodes.

like image 77
Mooing Duck Avatar answered Sep 02 '25 16:09

Mooing Duck