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