2

So i have an array of pointers that point to objects, and a pointer that points to each object elsewhere in my code. What i want is when i delete those other pointer. How do i rearrange my array of pointers so that there's no garbage values in the middle of it. I have a rearrange function that checks for NULL but the pointer doesn't point to NULL.

void Floor::rearrange(){
    for (int i=0;i<numEnemies;i++){
            if(Enemies[i] == NULL){
                    Enemies[i] = Enemies[i+1];
                    Enemies[i+1] = NULL;
            }
    }

}

damon
  • 31
  • 2

2 Answers2

3

Use automatically owning pointers. shared_ptr, weak_ptr and unique_ptr can automatically solve this problem for you with correct usage.

Using delete is a major code smell.

Puppy
  • 144,682
  • 38
  • 256
  • 465
3

It sounds like you want the pointers in the array to be weak_ptr then the other pointers should be shared_ptr.

That way, when the other pointer is deleted you can safely detect it.

Chris Drew
  • 14,926
  • 3
  • 34
  • 54