How to safely delete multiple pointers

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

    Why are you trying to delete pointers arbitrarily? Every dynamically allocated object is allocated in one place, by one owner. And it should be that one owners responsibility to ensure the object is deleted again.

    In some cases, you may want to transfer ownership to another object or component, in which case the responsibility for deleting also changes.

    And sometimes, you just want to forget about ownership and use shared ownership: everyone who uses the object shares ownersip, and as long as at least one user exists, the object should not be deleted.

    Then you use shared_ptr.

    In short, use RAII. Don't try to manually delete objects.

提交回复
热议问题