error with vector::reverse_iterator in debug mode but not in release

109 Views Asked by At

I use reverse_iterator to look up my vector and using pop_back to erase elements.But it causes some error in debug mode. My code is this:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct Student{
    string name;
    int score;
};

int main()
{
    vector<Student> testVec;
    testVec.push_back(Student{ "Lilei",50 });
    testVec.push_back(Student{ "YangFeifei",80 });
    testVec.push_back(Student{ "WuMing",80 });
    for (auto it = testVec.rbegin(); it != testVec.rend(); ++it){
        if (it == testVec.rbegin()) continue;
        while (it != testVec.rbegin()) {
            std::cout << &(*testVec.rbegin()) << ", ";
            std::cout << &(*it) << std::endl;

            testVec.pop_back();

            std::cout << &(*testVec.rbegin()) << ", ";
            std::cout << &(*it) << std::endl; // where error occur!
        }
    }
    std::cout << "Hello World!\n";
}
1

There are 1 best solutions below

1
dreamlax On

This documentation for std::vector<>::pop_back() says that:

Iterators and references to the last element, as well as the end() iterator, are invalidated.

Therefore, your it iterator is invalid after you called pop_back(). The behaviour of dereferencing this iterator is undefined, so your program's behaviour will be unpredictable.

For your particular case, it's possible that in debug builds there are some additional methods for the runtime to determine that you have made a mistake, but these checks may be costly for performance so may not be included in a release build. In any case, the behaviour is not guaranteed. The solution is to not use it after calling pop_back().