damon
damon

Reputation: 31

Deleting one of 2 pointers that point to the same thing

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;
            }
    }

}

Upvotes: 2

Views: 188

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

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.

Upvotes: 3

Puppy
Puppy

Reputation: 146930

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.

Upvotes: 3

Related Questions