读书人

留神使用STL容器的erase()

发布时间: 2012-12-24 10:43:14 作者: rapoo

小心使用STL容器的erase()



对于以下代码:

留神使用STL容器的erase()

如果是在for,while中对m_container迭代,删除其中符合条件的所有元素,就可能出现问题。


问题是:

在迭代容器的时候删除元素,可能导致迭代器失效(invalidation of iterators),产生未定义行为

(undefined behavior);

例如,对某个迭代器解引用所获得的值并不是执行erase()前这个迭代器指向的值,还有可能对未指向任何

元素的迭代器的解引用赋值而引发程序crash。

类似的问题代码像这样:



Scott Meyers在他的”Effective STL”中关于此问题的讨论中也使用了remove_if(),由此看来,他的确是提出了一些让STL effective的建议。


深入学习STL迭代器失效问题:

在google中搜索 stl iterator invalidation rules 可以获得很多有关STL迭代器失效的有关内容。


References:

1. STL remove_if() http://en.cppreference.com/w/cpp/algorithm/remove

2.More C++ Idioms/Erase-Remove   http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Erase-Remove

3.Effective STL, Item 32 - Scott Meyers

4.Cpp Invalid Iterators [对各种迭代器失效的情况进行了讲解分类]

http://www.angelikalanger.com/Conferences/Slides/CppInvalidIterators-DevConnections-2002.pdf

5.以下是stackoverflow上关于在迭代时删除容器中元素的讨论:

http://stackoverflow.com/questions/1604588/iterate-vector-remove-certain-items-as-i-go

http://stackoverflow.com/questions/3747691/stdvector-iterator-invalidation?rq=1

http://stackoverflow.com/questions/2874441/deleting-elements-from-stl-set-while-iterating?rq=1

http://stackoverflow.com/questions/1038708/erase-remove-contents-from-the-map-or-any-other-stl

-container-while-iterating/1038761#1038761

http://stackoverflow.com/questions/799314/difference-between-erase-and-remove?rq=1


Author: Garyelephant ,转载请注明来自http://garyelephant.me









读书人网 >软件架构设计

热点推荐