How to safely delete multiple pointers

前端 未结 8 1919
無奈伤痛
無奈伤痛 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:29

    There are some very rare cases where you might not be able to use a smart pointer (probably dealing with old code), but cannot use a simple "ownership" scheme either.

    Imagine you have an std::vector and some of the whatever* pointers point to the same object. Safe cleanup involves ensuring you don't delete the same whatever twice - so build an std::set as you go, and only delete the pointers that aren't already in the set. Once all the pointed-to objects have been deleted, both containers can safely be deleted as well.

    The return value from insert can be used to determine whether the inserted item was new or not. I haven't tested the following (or used std::set for a while) but I think the following is right...

    if (myset.insert (pointervalue).second)
    {
      //  Value was successfully inserted as a new item
      delete pointervalue;
    }
    

    You shouldn't design projects so that this is necessary, of course, but it's not too hard to deal with the situation if you can't avoid it.

提交回复
热议问题