Re: catching delete exceptions
On Wed, 6 Feb 2008 10:06:11 -0800 (PST), Stefano <posting@hotmail.it>
wrote:
Hi,
I'm trying to catch (I'd like to log them) delete exceptions.
For example
int* p;
p = new int;
delete p;
delete p; // this will throw an exception
but if I change my code in
int* p;
p = new int;
try
{
delete p;
delete p;
}
catch(...)
{
// Log
}
This will throw an exception and it's not handled.
See:
http://members.cox.net/doug_web/eh.htm
Is there a way to do this ?
No. There's no guarantee that double-deletion will cause an exception, and
there's even less of a guarantee that it will be a C++ exception. It's up
to you to use pointers correctly. In general, you should be using smart
pointers, which automatically delete the pointers they hold when their
lifetime ends, which (mostly) relieves you from having to delete them, and
smart pointers also help a great deal with exception safety.
Of course, it's harmless to delete a null pointer, so sometimes people do
this:
delete p;
p = 0;
// Now I can do the following without harm:
delete p;
This is valid when a pointer can be deleted before its lifetime actually
ends, such as in the destructor of the object that contains it, which also
deletes the pointer. You can either set the pointer to null to make
subsequent deletion attempts harmless, or you can track the lifetime in
some other way.
--
Doug Harrison
Visual C++ MVP