Testing if an object is deleted

Have a look at 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 pointing to the same object. I would like to determine if n2 was deleted using the n1 pointer test. But this test leads to an exception.

Is there a way to determine if an object has been deleted (or not deleted) using pointer n1?

+4
source share
3 answers

As far as I know, a typical way to handle this situation is to use pointers with reference counting as it does (like COM). There is a shared_ptr template class in Boost that can help ( http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm ).

+11
source

Not. Nothing in your code has a way to reach pointer n1 and change it when you destroy the object that the object points to.

To work, Node must (for example) maintain a list of all pointers to it, and you will have to manually register (i.e. call a method) every time you copy the value of a pointer. It would be very painful to work with.

+4
source

When you have an object, it will be in some place in memory. This value is for both n1 and n2 . When you delete an object, freeing up the memory that this object uses, the memory is invalid. Thus, you can never access those points n1 if they were deleted.

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

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

0
source

Source: https://habr.com/ru/post/1308654/


All Articles