I have a fairly simple question;
I have arrays which contain pointers to objects. I sometimes create mutated arrays from those arrays and only use them, let’s say, within a method. Aftwards I don’t need them. In this case I don’t want the pointed data to be destroyed as I keep using the original Array. What I don’t fully understand is what happens to the pointers ( not the data itself, but the pointers) that were created in my temporarily Array? How does Memory deal with them. As far as I know Pointers can only point to an address. You can’t “delete” them.
Anyone who can give me more insight? All this time I feel like I’m doing something wrong with memory.
In this case list is my “bag”, which is an object wrapper for an array implementation. However since it contains gabs between indexes I use getGapless to get a bag where the nullptr indexes are excluded.
I delete my bag at the end, but it doesn’t delete the actual content ( that is done with a different method ).
So when do those pointers in my “players” bag go out of scope?
virtual void processEntities(artemis::ImmutableBag<artemis::Entity*>& bag)
{
artemis::Bag<artemis::Entity*> * list = (artemis::Bag<artemis::Entity*>*)this->world->getGroupManager()->getEntities("HUMAN");
if(list == nullptr) return;//Kill function
artemis::Bag<artemis::Entity*> * players = list->getGapless();
for(int i=0; i<players->getCount(); i++)
{
for(int j=i+1; j < players->getCount(); j++)
{
if(intersects(*players->get(i),*players->get(j))){
std::cout << "Collide YEAH \n";
}
}
}
delete players;
}
Nope, don’t worry! You can think of pointers as being managed in the same way as
ints ordoubles (at least in terms of memory). The pointer itself is like anintthat happens to contain the address of some other object or array of objects. Once the pointer disappears from scope, the memory for the pointer itself will automatically be recovered.The exception would be if you’re doing something like
int** p = new int*[1], i.e. creating pointers withnew. Then you will at some point need todelete p.If you’re creating your pointers like
int* p = new int[size];(which is probably what you want), thenpitself is on the stack, which means you don’t need to concern yourself with memory deallocation, but the arrayppoints to is on the heap which means you will need to deallocate it at some point.