Some programmers like to set a pointer variable to null after releasing the pointee:
delete ptr;
ptr = 0;
If someone tries to release the pointee again, nothing will happen. In my opinion, this is wrong. Accessing a pointer after the pointee has been released is a bug, and bugs should jump in your face ASAP.
Is there an alternative value I could assign to a pointer variable that designates released pointees?
delete ptr;
ptr = SOME_MAGIC_VALUE;
Ideally, I would want Visual Studio 2008 to tell me "The program has been terminated because you tried to access an already released pointee here!" in debug mode.
Okay, it seems I have to do the checking myself. Anything wrong with the following template?
template <typename T>
void sole_delete(T*& p)
{
if (p)
{
delete p;
p = 0;
}
else
{
std::cerr << "pointee has already been released!\n";
abort();
}
}
No. Test for "0" when trying to delete
something if you really want to warn or error out about it.
Alternatively, during development you could omit ptr = 0;
and rely on valgrind to tell you where and when you're attempting a double free. Just be sure to put the ptr = 0;
back for release.
Edit Yes, people I know C++ doesn't require a test around delete 0
;
I am not suggesting if (ptr != 0) delete ptr;
. I am suggesting if (ptr == 0) { some user error that the OP asked for } delete ptr;
Assign NULL
after releasing a pointer. And before using it, check for its NULL
ity.. If it is null, report an error by yourself.
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