繁体   English   中英

调试断言失败-向量迭代器不可解除

[英]Debug assertion failed - Vector iterator not dereferencable

运行此代码时出现此运行时错误:

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中编译并运行,但是会破坏数据。

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

如果您需要更多源代码,请编写。 不幸的是,由于这是一个复杂的程序,因此很难发布所有代码。

考虑到当您按值将项添加到向量中时它不起作用,但是当您泄漏指针时它会起作用,我有95%的信心认为AlienShip的副本构造AlienShip会进行浅表复制,从而导致问题。

编辑:请注意, m_alienShipList.push_back(AlienShip(position, speed, m_screeSize, m_alienShipTexture)); 会导致您的类的副本,如果副本构造函数无法正常运行,则会在以后导致问题。

实际上,如果您粘贴的AlienShip定义是正确的,则实际上只有默认的复制构造函数可能会做错事(由于您拥有自己的析构函数,因此进一步加强了这一点)。

实现深拷贝的副本构造函数,或者更佳地重写类以使用RAII为您管理内存,以使默认副本正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM