向量访问冲突,空索引,迭代器不兼容

时间:2015-11-16 00:58:20

标签: c++ memory-management vector shared-ptr access-violation

我正在写游戏,而且我在内存管理方面苦苦挣扎。我遇到了一些不同的运行时错误。这是一些代码:

在关卡中:

typedef std::shared_ptr<Projectile> projectile_ptr;
std::vector<projectile_ptr> projectileList;

所以我们会有多个射弹,存储在矢量(或列表?)中。我将它们添加到矢量中:

void Level::addProjectile(projectile_ptr ptr)
{
    projectileList.push_back(ptr);
}

//somewhere else in the code
projectile_ptr projectile(new Projectile(PT_BULLET, true, &p));
game->level->addProjectile(projectile);

现在在其他2个地方我读了这个清单。在Game类中,当我在渲染之前更新游戏状态时,以及在Renderer中将要绘制射弹时。

我遍历这样的矢量:

for (std::vector<projectile_ptr>::iterator it = game->level->projectileList.begin(); it != game->level->projectileList.end();) {
    Projectile & projectile = *(*it); 

    if (projectile.isDestroyed) {
        it = game->level->projectileList.erase(it);
        break;
    }
    projectile.calculatePosition(ticks);
    //some other calculations
    ++it;
}

for (std::vector<projectile_ptr>::iterator it = game->level->projectileList.begin(); it != game->level->projectileList.end(); ++it) {
    Projectile & projectile = *(*it);
    if (projectile.isReadyToRender) {
        //drawing code
    }
}

上面的代码有什么问题,为什么我会遇到奇怪的运行时?

Also look on the attached screenshot:

如何在向量中有空格,因为shared_ptr负责删除对象?

我在擦除和渲染循环中都获得了运行时。请帮忙。

0 个答案:

没有答案