I was wondering if there is a possibility to catch errors like this in C++:
object* p = new object;
delete p;
delete p; // This would cause an error, can I catch this?
- Can I check if the pointer is valid?
- Can I catch some exception?
I know I could set the pointer p to NULL after the first object deletion. But just imagine you wouldn’t do that.
I don’t think you can catch this kind of error because I think the result is undefined behaviour. It might do nothing, it might crash, it might just corrupt the memory and cause a problem later down the line.
If you found it did something specific with your current compiler you could try and handle that, but it might do different things in debug and release, and different again when you upgrade the compiler version.
Setting the pointer to null has been suggested, but I think you would be better off using smart pointers and not deleting them at all.