Search code examples
c++pointersmemorydelete-operator

How to safely delete multiple pointers


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 = q;

delete r; r = NULL; // ok
// delete q; q = NULL; // NOT ok
// delete p; p = NULL; // NOT ok

How to safely delete it without multiple delete? This is especially difficult if I have a lot of objects which having pointers all pointing to the same address.


Solution

  • The answer, without resorting to managed pointers, is that you should know whether or not to delete a pointer based on where it was allocated.

    Your example is kind of contrived, but in a real world application, the object responsible for allocating memory would be responsible for destroying it. Methods and functions which receive already initialized pointers and store them for a time do not delete those pointers; that responsibility lies with whatever object originally allocated the memory.

    Just remember that your calls to new should be balanced by your calls to delete. Every time you allocate memory, you know you have to write balancing code (often a destructor) to deallocate that memory.