How to safely delete multiple pointers

前端 未结 8 1807
無奈伤痛
無奈伤痛 2021-01-03 02:06

I have got some code which uses a lot of pointers pointing to the same address. Given a equivalent simple example:

int *p =  new int(1);
int *q = p;
int *r =         


        
8条回答
  •  一生所求
    2021-01-03 02:18

    I would say that some times, smart pointers can actually slow down your application, albiet not by a lot. What I would do is create a method, like so:

    void safeDelete(void **ptr)
    {
      if(*ptr != NULL)
      {
         delete ptr;
         *ptr = NULL;
      }
    }
    

    I'm not sure if I did it 100% correctly, but what you do is you pass the pointer into this method that takes the pointer of a pointer, checks to make sure the pointer it points to isn't set to NULL, then deletes the object and then sets the address to 0, or NULL. Correct me if this isn't a good way of doing this, I'm also new to this and someone told me this was a great way of checking without getting complicated.

提交回复
热议问题