Issue with pointer delete

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
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());
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.
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.
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.
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
Topic archived. No new replies allowed.