为什么我的应用程序在删除时崩溃

Why does my app crash at delete?

本文关键字:崩溃 删除 我的 应用程序 为什么      更新时间:2023-10-16
while(!m_RemoveNodeList.empty())
{
    list<CNode *>::const_iterator const it = m_RemoveNodeList.begin();
    CNode * const pNode = *it;
    ASSERT(pNode != NULL);
    m_NodeList.remove( pNode );
    delete pNode; // crashing here
    m_RemoveNodeList.pop_front();
}
上面的

有时会在删除时崩溃,并产生读冲突异常。会不会是我不小心双重删除了?

m_NodeList和m_RemoveNodeList的类型都是
 std::list<CNode *>

我应该提到CNode是其他几个类的基类。然而,这些类都没有在析构函数

中做任何事情。

你的代码没有明显的崩溃,看起来很好。

只有当副本 CNode*存储在list<CNode*>中时才会崩溃;这会让你得到多个delete。(@ paul .estalella在评论中提到过)

您可以尝试以下方法来捕获,如果有重复 CNode*

map<CNode*, int> duplicate;
while(m_RemoveNodeList.size() > 0)
{
    list<CNode *>::const_iterator const it = m_RemoveNodeList.begin();
    CNode * const pNode = *it;
    if(duplicate.find(pNode) == duplicate.end())
      duplicate[pNode] = 1;
    else
      cout<<"Caught: "<<pNode<<endl;
// ...
}

pNode只是对原始文件的引用,而不是副本。不确定remove做了什么,但它确实做了原始的,你有一个双重删除