std :: list :: clear会使std :: list :: end iterator失效吗?

Ric*_*ian 11 c++ stl stdlist visual-studio-2012

检查此代码:

#include "stdafx.h"
#include <list>

int _tmain(int argc, _TCHAR* argv[])
{
    std::list<int> mylist;
    mylist.push_back(1);
    std::list<int>::iterator i = mylist.end();
    if( i == mylist.end() )
        printf( "end is end\n" );

    mylist.clear();
    if( i == mylist.end() )
        printf( "never get here because Microsoft seems to "
                "think the iterator is no longer safe.\n" );

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在,根据cplusplus.com,这不应该是一个问题,在发布模式下,我认为这很好,并没有真正引起任何问题,但调试变得不可能,因为这只是保释而不让我继续.有什么指针吗?

Mik*_*our 11

其他答案指出,通常,当容器被清除时,您不能依赖容器的过去迭代器保持有效.但是,列表的过去结束迭代器确实应该保持有效:

C++ 11 23.3.5.4/3 效果:仅使迭代器和对已擦除元素的引用无效.

过去的结束迭代器不引用任何元素,因此不应该失效.

  • 谢谢,Mike和@DavidRodríguez-dribeas.是的,这是Visual C++ 2012`std :: list`实现中的一个错误.这是Visual C++ 2010的回归.请注意,`erase`同样被破坏.几个月前我检查了这个bug的修复程序,修复程序将出现在Visual C++标准库的下一个发布版本中.修复程序修复了"擦除"和"清除".(此错误是由客户报告的,但不是通过Microsoft Connect报告的,因此我没有可以推荐您的链接.) (2认同)