今天检查出代码的一个异常,也怪自己太大意,习惯了ctrl+c/v。。
描述如下:
map<UINT, CModule*> m_ModulePoints;
for (map<UINT, CModule*>::iterator it = m_ModulePoints.begin(); it != m_ModulePoints.end(); it++)
{
CModule *pModule= (CModule*)(*it).second;
if (.......)
{
delete pModule;
m_ModulePoints.erase(it);
}
}
那么问题来了,iterator it 被erase后,for循环仍旧对齐进行++操作,导致异常。在没有使用erase的情况下,我们确实可以使用这样的for循环结构遍历map,一旦需要erase,则不允许这样做。
正确的做法之一:
for (map<UINT, CModule*>::iterator it = m_ModulePoints.begin(); it != m_ModulePoints.end(); )
{
CModule *pModule= (CModule*)(*it).second;
if (.......)
{
delete pModule;
it = m_ModulePoints.erase(it);
}
else
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>it++;
<span style="white-space:pre"> </span>}
}
利用erase函数的返回值可以避免这一问题。
另一种做法是:
for (map<UINT, CModule*>::iterator it = m_ModulePoints.begin(); it != m_ModulePoints.end(); )
{
CModule *pModule= (CModule*)(*it).second;
if (.......)
{
delete pModule;
it = m_ModulePoints.erase(it++);
}
}