سؤال

When I am iterating through "m_itFileBuffer" stringlist container, I get an exception while fetching the value from the iterator.This line of code works most of the times but only some time it gives exception.In my code I am setting "m_itFileBuffer" iterator to different values. the part of the code is given below

StringList m_listFileBuffer; //this contains list of CString`s, I read from file and insert into this.
StringList::iterator m_itFileBuffer;
....
....
....
....
....
{
    bool notEmpty = (m_itFileBuffer != m_MylistFileBuffer.end());

    if (notEmpty)
    {

        m_strLine = static_cast<CString>(*m_itFileBuffer);//Here i get exception 

        ++m_itFileBuffer;
    }
}

Below is exception which i get in output window:

Severity: Critical Error (10 - 'System Crit.'), Returncode: 0x80040835, Error No.: 0 (access violation)
Description: C system exception code: C0000005

Any help, why i am getting this exception? Also, How can we reset the iterator?

هل كانت مفيدة؟

المحلول

I assume StringList is actually:

typedef std::list<CString> StringList;

Maybe you should consider using std::string instead of CString.

Now coming to the iteration through the list. The code you use to iterate looks strange to me. It would be simpler to do it like this:

for (StringList::/*const_*/iterator it=m_listFileBuffer.begin(); it != m_listFileBuffer.end(); ++it)
{
   /*const*/ CString& strLine = *it; //no need for static cast
   std::cout << (LPCTSTR) strLine << std::endl;
}

If you have Visual Studio 2010 (contains some of the C+11 stuff implemented) you can write the loop more concisely with auto:

for (auto it = begin(m_listFileBuffer); it != end(m_listFileBuffer); ++it)
{
   /*const*/ CString& strLine = *it; //no need for static cast
   std::cout << (LPCTSTR) strLine << std::endl;
}

EDITED by sehe:

With full C++11 support, simply write

for (/*const*/ auto& strLine : m_listFileBuffer)
    std::cout << (LPCTSTR) strLine << std::endl; 

EDITED by ds27680:

Please see also the comments...

To answer also your question related to the crash, this can happen due to various reasons. I will enumerate some of the most obvious ones:

  1. The iterator is initialized with the begin of one list but checked on the end of another list. comparing iterators from different containers is a bad idea
  2. You are doing operations (in the same or another thread) on the list that invalidate the iterator but you are using it afterwards. I.e. m_listFileBuffer.erase(it);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top