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.
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.
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With