How to safely delete multiple pointers

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

    The problem you are facing is that the ownership semantics in your program are not clear. From a design point of view, try to determine who is the owner of the objects at each step. In many cases that will imply that whoever creates the object will have to delete it later on, but in other cases ownership can be transferred or even shared.

    Once you know who owns the memory, then go back to code and implement it. If an object is the sole responsible for a different object, the it should hold it through a single-ownership smart pointer (std::auto_ptr/unique_ptr) or even a raw pointer (try to avoid this as it is a common source of errors) and manage the memory manually. Then pass references or pointers to other objects. When ownership is transfered use the smart pointer facilities to yield the object to the new owner. If the ownership is truly shared (there is no clear owner of the allocated object) then you can use shared_ptr and let the smart pointer deal with the memory management).

    0 讨论(0)
  • 2021-01-03 02:32

    It is not possible to know whether the memory referenced by a pointer has already been deleted, as in your case.
    If you can not use a library with smart pointers, that do reference counting, and you can not implement your own reference counting schema (if indeed you need to do what you describe in your post) try to call realloc on the pointers.
    I have read in other posts that depending on the implementation the call to realloc may not crash but return back a null pointer. In this case you know that the memory referenced by that pointer has been freed.
    If this works as a dirty solution, it will not be portable, but if you have no other option, try it. The worse of course will be to crash your application :)

    0 讨论(0)
提交回复
热议问题