Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test, if object was deleted

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?

like image 410
justik Avatar asked Dec 07 '22 03:12

justik


2 Answers

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).

like image 96
Guido Domenici Avatar answered Dec 09 '22 16:12

Guido Domenici


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.

like image 33
unwind Avatar answered Dec 09 '22 17:12

unwind