`unordered_map::erase()` 是否总是立即调用析构函数?

huangapple go评论87阅读模式
英文:

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_backpop_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.

huangapple
  • 本文由 发表于 2023年8月5日 03:00:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定