Pointers to elements of STL containers

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 23:07:59

std::list, std::set, and std::map guarantee that the iterators (including simple pointers) will not be invalidated when a new element is added or even removed.

As Armen mentioned std::list, std::set, and std::map are guaranteed to only invalidate the removed iterator. In the case of boost::unodered_map, the modifiers may indeed invalidate iterators.

http://www.boost.org/doc/libs/1_38_0/doc/html/boost/unordered_map.html

The C++ Standard places stringent rules on the validity of references / iterators. For each container, each method documents which elements may be moved (invalidating references and iterators).

The Node Based Containers: list, map, set, multimap and multiset guarantee that references and iterators to elements will remain valid as long as the element is not removed from the container.

Your use case is therefore one of the corner cases where using a list for storage is good, because of the invalidation guarantees that list offer.

I think it's better to use std::list <shared_ptr <ABC> > instead of passing a pointer. It's good practice to delegate memory management (see scott meyers effective c++)

This has mulitple advantages:

  • you can share them and pass them without the headache of freeing them
  • garbage collection of your pointers
  • you don't pass a pointer in the first place
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!