How to safely delete multiple pointers

前端 未结 8 1811
無奈伤痛
無奈伤痛 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).

提交回复
热议问题