[英]Memory in use issue using marmalade SDK
我有子彈班。 我嘗試通過以下代碼實例化它:
我總是斷言有一個正在使用的內存..為什么?
在另一個稱為ship的類中:
if (g_Input.isKeyDown(s3eKeySpace))// && Canfire)
{
Bullet *bullet = new Bullet();
bullet->Init(SHIP_BULLET);
bullet->setPosition(Position.x, Position.y - 20);
Bullets->push_back(bullet);
Canfire = false;
}
這稱為導致內存仍在使用的每個幀:
for (list<Bullet*>::iterator it = Bullets->begin(); it != Bullets->end();)
{
(*it)->Update(dt);
if ((*it)->IsDestroyed)
{
Canfire = true;
it = Bullets->erase(it);
}
else
{
it++;
Canfire = false;
}
}
船級的破壞者
Ship::~Ship()
{
for (std::list<Bullet*>::iterator it = Bullets->begin(); it != Bullets->end(); ++it)
delete *it;
delete Bullets;
}
class Bullet
{
public:
Bullet();
~Bullet();
public:
void Init(BulletTypes bulletType);
void Update(float dt);
void Render();
CIw2DImage* Image; // curr image
}
void Bullet::Init(BulletTypes bulletType)
{
BulletType = bulletType;
if (BulletType == SHIP_BULLET)
{
Image = Iw2DCreateImage("textures/ship_bullet.png");
if (Image == nullptr)
return;
}
}
Bullet::~Bullet()
{
delete Image;
}
執行此代碼會導致泄漏:
for (list<Bullet*>::iterator it = Bullets->begin(); it != Bullets->end();)
{
(*it)->Update(dt);
if ((*it)->IsDestroyed)
{
Canfire = true;
it = Bullets->erase(it);
}
else
{
it++;
Canfire = false;
}
}
基本上是從容器中刪除動態分配的元素,丟失對它的任何引用,因此無法再釋放其內存。 顯然,調用Ship析構函數只會釋放列表中當前包含的元素,但不包括在迭代中刪除的元素。
我建議將此作為解決方法:
for (list<Bullet*>::iterator it = Bullets->begin(); it != Bullets->end();)
{
(*it)->Update(dt);
if ((*it)->IsDestroyed)
{
Canfire = true;
delete *it; // it now points to invalid address
it = Bullets->erase(it);
}
else
{
it++;
Canfire = false;
}
}
另一個選擇是將所有卸下的子彈存儲在Ship類中的其他某個容器中,以防在銷毀子彈后可以對其進行引用。 這個想法的問題是,您有很多被破壞的子彈占用了內存,並且不得不提出一種解決方案,一旦它們真的無用,如何將其刪除。
如果您對此感到困惑,則使用std :: shared_ptrs而不是列表中的原始指針可以解決您的問題(對性能造成輕微影響)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.