开发者

Test, if object was deleted

开发者 https://www.devze.com 2022-12-28 18:51 出处:网络
Look to the following code, please: class Node { private: double x, y; public: Node (double 开发者_开发知识库xx, double yy): x(xx), y(yy){}

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?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号