Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 901
rnd_nr_gen Avatar asked Oct 14 '10 10:10

rnd_nr_gen


2 Answers

Your tool is shared_ptr of the boost library. Take a look at the documentation: http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm

Example:

void func() {
  boost::shared_ptr<int> p(new int(10));
  boost::shared_ptr<int> q(p);
  boost::shared_ptr<int> r(q);

  // will be destructed correctly when they go out of scope.
}
like image 127
WolfgangP Avatar answered Oct 05 '22 05:10

WolfgangP


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.

like image 35
meagar Avatar answered Oct 05 '22 06:10

meagar