Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c++ - Expression: cannot increment value-initialized iterator (Error in Debug, but not in Release mode - Visual Studio)

I have the problem that some parts of my code run in the Release mode without a problem, but errors appear in the Debug mode.

Setup: c++ 17 - Visual Studio 2019

To show the difference I wrote a little testcode:

int main()
{
   //Vector containing 20 lists with length of 10 each. Every Element = 10
   std::vector<std::list<int>> test(20, std::list<int>(10,10));

   std::cout << test[6].front() << std::endl; //test if initialization worked

   std::list<int>::iterator test_iter;
   for (test_iter = test[6].begin(); test_iter != test[6].end(); test_iter++)
   {
       std::cout << *test_iter << std::endl;
       test[6].erase(test_iter);
   }
}

In Release it works fine

But in Debug I get this

Does anyone have an idea why there is a difference between the both mode and how I can adjust it, so the Debug mode works fine as well?

Thanks for your help in advance!

Best regards David

question from:https://stackoverflow.com/questions/65841810/expression-cannot-increment-value-initialized-iterator-error-in-debug-but-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is not so much that it doesn't work in debug, as it is that it appears to work in release - the code is equally broken in both, but the debug version of the library has some extra error-checking code.
The error message is a bit cryptic, but what it's trying to say is that you're attempting to increment an iterator that can't be incremented.

This happens because test[6].erase(test_iter); invalidates test_iter, and using it after that is undefined.

erase returns an iterator to the element following the erased element, and you can use this iterator instead of incrementing:

for (test_iter = test[6].begin(); test_iter != test[6].end(); /* empty */)
{
    std::cout << *test_iter << std::endl;
    test_iter = test[6].erase(test_iter);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...