Aug 20, 2012 at 11:59pm UTC
Hello All,
I'm creating some projectiles and have an issue removing them.
The projectiles are created locally with a pointer and are stored into a vector. When I go to remove the pointer from the vector my program crashes. In my research on the issue I realize that pointers cannot point to local variables.
So this is a 2 part question, what would be a better solution to create multiple projectiles? I'm currently doing this:
1 2 3 4 5 6 7 8
if (_elapsedTime >= (_timer + delay))
{
_timer += delay;
CProjectile* projectile = new CProjectile();
CGame::GetManager().Add(projectile);
projectile->SetMoveSpeed(CGame::GetInput().GetMouseX(), CGame::GetInput().GetMouseY());
projectile->SetPosition(GetSprite().GetPosition().x, GetSprite().GetPosition().y);
}
Should I just be doing:
1 2 3 4
CProjectile projectile;
CGame::GetManager().Add(projectile);
projectile.SetMoveSpeed(CGame::GetInput().GetMouseX(), CGame::GetInput().GetMouseY());
projectile.SetPosition(GetSprite().GetPosition().x, GetSprite().GetPosition().y);
As always, help is greatly appreciated.
Last edited on Aug 20, 2012 at 11:59pm UTC
Aug 21, 2012 at 12:03am UTC
I'd probably go with the first, and use a boost::ptr_vector internally or something.
Btw, you can just do:
CGame::GetManager().Add(new CProjectile());
Aug 21, 2012 at 1:40am UTC
Well I have to make 2 function calls immediately after I instantiate so I can't just make the new object and not have a reference of it.
Haven't used boost pointers yet, maybe i'll look into that.
Aug 21, 2012 at 3:33am UTC
Why can't you set up a new ctor to accept the values you're setting?
Once you're CGame dtor is called, you can delete all of the projectiles that way.
Aug 21, 2012 at 4:16pm UTC
Well this is more an issue with memory management, isn't it better to delete the heap objects that aren't being used anymore?
i.e. the projectiles that are outside of the window and are not being drawn?
Or is that a waste of time to try and free up the memory.
Aug 21, 2012 at 6:28pm UTC
So I seem to have somewhat solved this by doing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void CObjectManager::Remove(CEntityManager* obj)
{
for (int i = 0; i < _mEntity.size();)
{
if (_mEntity.at(i) == obj)
{
CEntityManager* pObj = _mEntity.at(i);
delete pObj;
_mEntity.erase(_mEntity.begin() + i);
}
else
i++;
}
}
But after it finishes removing the objects it crashes saying:
"The application has requested the Runetime to terminate it in an unusual way."
I'm assuming that something in vector is being called elsewhere asynchronously and causing this to crash? Or am I way off here...
Last edited on Aug 21, 2012 at 6:28pm UTC