Strange behavior with std::map::iterator's pos

2019-08-28 05:06发布

问题:

From what I understand, the following program

#include <map>

int main()
{
    std::map<int,int> foo;
    std::map<int,int>::iterator start = foo.begin();
    while (start++ != foo.end())
        ;
}

should terminate, but it instead loops indefinitely using libstdc++ 4.7.2. Is the behavior exhibited by this program correct, or is there a bug in the standard library? What are the operational properties of operator++(int) on iterators?

回答1:

The map is empty, so the first start++ is attempting to increment an end iterator which is undefined behaviour. From std::map::end():

Returns an iterator to the element following the last element of the container. This element acts as a placeholder; attempting to access it results in undefined behavior.

Even though the post increment start++ returns the original value of start, which in this case would be end(), it is unreasonable to expect the loop to terminate due to the presence of undefined behaviour.

To correct, check if start is equal to foo.end() before incrementing or dereferencing.