Like the codes below, m_vSprites is a vector of shred_ptr, if one of his elements update fail, I would like to erase it from the vector, but my codes crash when I would like to using erase. But I don't why, anyone can help?
The reason I need to use erase is because my application would continually add elements in the vector, but would also continually erase objects from vector if some elements meets their killing conditions. if I didn't erase it, the vector would become huge as the program works!
RECT rcOldSpritePos;
typedef boost::shared_ptr<Sprite> SmartSprite;
vector<SmartSprite>::iterator siSprite;
for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end();)
{
// Save the old sprite position in case we need to restore it
rcOldSpritePos = (*siSprite)->getPosition();
if (!((*siSprite)->update()))
{
// Kill the sprite
//siPreviousSprite = siSprite-1;
siSprite = m_vSprites.erase(siSprite);
}
else
{
siSprite++;
// See if the sprite collided with any others
if (checkSpriteCollision(*siSprite))
// Restore the old sprite position
(*siSprite)->setPosition(rcOldSpritePos.left, rcOldSpritePos.top);
}
}
I have changed the codes as someone suggested, but still failed in the erase function, Please anyone have some suggestions?
Some more information how I add an element in the vecotr
Any problem here?
SmartSprite sprite;
if (0 < enemies.size())
{
// Pick a random enemy to drop bomb
size_t nRandEnemy = (rand() % enemies.size());
RECT rRandEnemy = enemies.at(nRandEnemy)->getPosition();
sprite.reset(new BombSprite(m_system, rRandEnemy.right-OBJECTSIZE/2,
rRandEnemy.bottom));
m_vSprites.push_back(sprite);
}
My sprite class didn't have any destructor...
one more information is, while I debug, found it crash in erase internal function: _Destroy(_Mylast - 1, _Mylast);
problem solved!, the reason is in my Sprite class, I wrap it as a smart pointer, and created another smart pointer as its member variable. now I didn't use the smart pointer member variable, and the system didn't crash again.... I will continue to think about why I can't use a smart pointer inside that class, when erase sprite from vector, does it matter in his member variable? do I still need to delete that member variable if only use raw pointer instead of suing smart pointer?