views:

153

answers:

4

Look to the following code, please:

class Node
{
private:
    double x, y;
public:
    Node (double xx, double yy): x(xx), y(yy){}
};

int main()
{
  Node *n1 = new Node(1,1);
  Node *n2 = n1;

  delete n2; 
  n2 = NULL;

  if (n1 != NULL) //Bad test
  {
     delete n1;   //throw an exception
  }
}

There are two pointers n1, n2 pointed to the same object. I would like to detect whether n2 was deleted using n1 pointer test. But this test results in exception.

Is there any way how to determine whether the object was deleted (or was not deleted) using n1 pointer ? Thanks for your help.

+4  A: 

No. Nothing in your code has a way of reaching the n1 pointer and changing it when the pointed-to object's is destroyed.

For that to work, the Node would have to (for instance) maintain a list of all pointers to it, and you would have to manually register (i.e. call a method) every time you copy the pointer value. It would be quite painful to work with.

unwind
+11  A: 

As far as I know the typical way to deal with this situation is to use reference-counted pointers, the way (for example) COM does. In Boost, there's the shared_ptr template class that could help (http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm).

Guido Domenici
+1: boost::shared_ptr is really efficient. You don't even have to call delete yourself and can provide your own destructor function for the pointed values.
ereOn
A: 

When you have an object it will be at some place in memory. This is the value for both n1 and n2. When you delete the object, by releasing the memory that object used, the memory is invalid. So you can never access anything n1 points to, if it was deleted.

I suggest creating a wrapper object, which contains a counter and a pointer to the object. When you want to point to the actual object, instead you have to point to the wrapper, and when you want to delete the object, you actually call a method on the wrapper:

If you want to point to the object, you should increase the counter of the wrapper, and point to the wrapper. If you want to delete the object, you should decrease the counter and set the pointer to the wrapper to null. If the counter of the wrapper reaches zero, you can safely delete the actual object and then the wrapper.

Pindatjuh
A: 

Thanks for your answers...

Could you give any example of such object counter (or wrapper), please ?

justik
This is not an answer. Delete this and post it as a comment, or edit it into your original question.
Tyler McHenry