c ++从列表中删除时访问冲突读取位置

c++ Access violation reading location while erasing from list

我有以下 C++ 代码:

typedef std::list< Volume >::iterator   pVolume;
typedef std::list< pVolume >::iterator  ppVolume;
void Node::delVolume( pVolume _volume )
{
    for( ppVolume it = m_volumes.begin( ); it != m_volumes.end( ); )
        if( (*it) == _volume )
        {
            it = m_volumes.erase( it );
            break;
        }
        else
            it++;
}

出现错误

Unhandled exception at 0x009a3c79 in Delone3D.exe: 0xC0000005: Access violation reading location 0xfeeefef2.

正是在擦除时。调试显示 "it" 和“_volume”都不是空指针。

发生这种情况的其他原因可能是什么?

您显示的代码是正确的,您的应用程序中的其他地方似乎有问题。内存模式 0xfeeefef20xfeeefeee 上方的几个地址)表示已释放动态内存,请参阅 here

顺便说一句,您可以大大简化代码:

// for std::list, as in your example
m_volumes.remove(_volume);

// for std::vector and std::deque
auto itr = std::remove(m_volumes.begin(), m_volumes.end(), _volume);
m_volumes.erase(itr, m_volumes.end());

我找到了产生错误的地方。但是我不知道为什么。

我的整个代码都作为抽象事件的继承者实现 class

class Event
{
public:
    Event( ) { }
    ~Event( ) { }

    virtual void Implement( void ) abstract;
    virtual void ReturnColors( void );      
private:
};

有指向事件的指针的双端队列

std::deque< Event * >   m_triangulationEvents;

使用方式如下

void Delaunay3D::nextEvent( )
        {
            if( !m_triangulationEvents.empty( ) )
            {
                m_prevEvent->ReturnColors( );

                Event * cur = m_triangulationEvents.front( );
                m_triangulationEvents.pop_front( );
                cur->Implement( );

                delete m_prevEvent;
                m_prevEvent = cur;
            }
        }

问题在

delete m_prevEvent;

字符串。评论它或使用

m_prevEvent.~Event( );

应用效果良好。谢谢大家。

P.S。 @TheOperator 感谢您提到释放的动态内存