英文:
Does `unordered_map::erase()` always call the destructor immediately?
问题
如果我调用myMap.erase(1);
,Foo
的析构函数是否总是会立即被调用?或者标准库是否允许暂时保留Foo
的实例,直到它想要释放,或者稍后重新使用它?(我理解当地图本身被销毁时,最终一切都将被适当地销毁。)
英文:
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.)
答案1
得分: 3
我查看了https://eel.is/c++draft/#containers,并且似乎并不实际需要。销毁地图,以及复制或移动到容器需要销毁元素,但我只看到一个明确需要销毁的变异方法是pop_back
和pop_front
。
从理论上讲,似乎地图可以包含一个内部缓存的“已释放”节点,以便将来插入时重用,如果这样做,似乎实际上并不需要销毁和重新创建数据本身。至少直到调用map
析构函数为止。
这可能是C++规范中的一个疏漏,我会感到震惊如果有人实现了一个地图,即使他们缓存节点,也没有销毁和重新创建数据。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论