调试断言失败-矢量迭代器不可取消引用

Debug assertion failed - Vector iterator not dereferencable

本文关键字:迭代器 不可取 可取消 引用 断言 失败 调试      更新时间:2023-10-16

运行以下代码时出现运行时错误:

void AlienShipManager::Update(float timeDelta, 
        BulletManager* bulletManager,
        ParticleManager* particleManager,
        GameStringSystem* stringBatch)
{
    unsigned int i = 0;
    while (i < m_alienShipList.size())
    {
        AlienResult result = m_alienShipList[i].Update(timeDelta, bulletManager);
        switch (result)
        {
            case AlienResult::Dead:
                break;
            default:
                break;
        }
            ++i 
    }
}

在线

AlienResult result = m_alienShipList[i].Update(timeDelta, bulletManager);

下面是我如何将AlienShip添加到向量类:

m_alienShipList.push_back(AlienShip(position, speed, m_screeSize, m_alienShipTexture));

如果我有机会,错误也会出现:

AlienShip* newAlien = new AlienShip(position, speed, m_screeSize, m_alienShipTexture);
    m_alienShipList.push_back(*newAlien);
    delete newAlien;

但如果我将其更改为:,则不会出现

AlienShip* newAlien = new AlienShip(position, speed, m_screeSize, m_alienShipTexture);
    m_alienShipList.push_back(*newAlien);

从而导致巨大的存储器泄漏。

这就是我的AlienShip类的外观:

#pragma once
#include "Body.h"
#include "BulletManager.h"
#include "ParticleManager.h"
enum AliensShipState
{
    flying,
    dying,
    dead,
    escaped
};
enum AlienResult
{
    No,
    Hit,
    Dying,
    Dead,
    Escaped
};
class AlienShip : public Body
{
public:
    AlienShip(void);
    AlienShip(float2& position, float2& speed, float2* screenSize, ID3D11Texture2D* alienTexture);
    ~AlienShip(void);
    AlienResult Update(float timeDelta, BulletManager* bulletManager);
    void Draw(BasicSprites::SpriteBatch^ spriteBatch);
protected:
    float m_baseY;
    AliensShipState m_state;
    float2* m_screenSize;
};

AlienShip类继承自Body类,Body类中有Sprite类,后者中有另一个向量。但由于Sprite类在其他地方运行得很好,我不认为它是错误的来源。

我想知道为什么会发生这种情况,因为我找不到删除临时对象和损坏向量迭代器之间的关系,如果它已经损坏了。

程序也在Release中编译和运行,但存在一些数据损坏。

我正在使用Visual Studio 2012 Beta for Windows 8。

如果你需要更多的源代码,请写。不幸的是,发布所有代码非常困难,因为这是一个复杂的程序。

考虑到按值将项添加到向量时它不起作用,但当泄漏指针时它起作用,我有95%的信心,AlienShip的复制构造函数会执行浅复制,从而导致问题。

编辑:请注意,m_alienShipList.push_back(AlienShip(position, speed, m_screeSize, m_alienShipTexture));会导致类的副本,如果副本构造函数工作不正常,稍后会导致问题。

事实上,如果您粘贴的AlienShip定义是正确的,那么实际上只有默认的复制构造函数可能会做错误的事情(您有自己的析构函数这一事实进一步强化了这一点)。

要么实现一个执行深度复制的复制构造函数,要么更优选地重写您的类,使用RAII为您管理内存,以便默认副本是正确的。