Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::list::clear invalidate std::list::end iterator?

Check this code:

#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;
}

Now, according to cplusplus.com this shouldn't be a problem, and in release mode, I think this is fine and doesn't cause any issues really, but debugging becomes impossible as this just bails without letting me continue. Any pointers?

like image 934
Richard Fabian Avatar asked Feb 01 '13 13:02

Richard Fabian


People also ask

How do you clear a STD list?

list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0.

Is iterator valid after erase?

Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated.

When should an iterator be treated as invalid?

An Iterator becomes invalidate when the container it points to changes its shape internally i.e. move elements from one location to another and the initial iterator still points to old invalid location.

Should I use std :: list?

Consider using std::list if: You need to store many items but the number is unknown. You need to insert or remove new elements from any position in the sequence. You do not need efficient access to random elements.


1 Answers

Other answers point out that, in general, you can't rely on a container's past-the-end iterator remaining valid when the container is cleared. However, the past-the-end iterator of a list should indeed remain valid:

C++11 23.3.5.4/3 Effects: Invalidates only the iterators and references to the erased elements.

The past-the-end iterator does not refer to any element, so should not be invalidated.

like image 93
Mike Seymour Avatar answered Oct 13 '22 07:10

Mike Seymour