简体   繁体   中英

c++ iterator operation do not check overflow?

Once I wrote a line:

while(++itr!=container.end()) 
{
   do something here
}

Even after itr passed end(), the condition is still true. I am puzzled. I thought operator++ should check boundaries. But it seems not. Here is a test program:

int main()
{
    vector<int> x;
    vector<string> y;
    x.push_back(10);
    y.push_back("test");
    auto itr = x.end();
    assert(itr == x.end());
    // this line makes itr past end
    ++itr;
    // this line is true
    assert(itr != x.end());
    // this line doesn't report any address issue or segment fault
    cout << *itr << endl;
    auto itry = y.end();
    assert(itry == y.end());
    ++itry;
    //  no error report
    assert(itry != y.end());
    //  report segment fault
    cout << *itry << endl;
    return 0;
}

Is it true that iterator in std c++ do not check past end or before begin() for -- operator?

This is how they work and this is for a performance reason. Iterators are modeled after pointers, pointer don't check for boundaries on increment.

You will get undefined behavior though if you increment past end() .

yep.

    while(++itr!=container.end()) 
    {
       do something here
    }
if itr==end() ,++itr can be anything!
so,you must write :
    if(it != xxx.end())
    {
        while(++it != xxx.end())
        {
             do sth
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM