Hack of the day: Safe delete
February 3, 2011
If you free up memory in C++, you should also set the pointer to NULL. If you double delete memory, your application will crash!
Because I’m a lazy coder, I’m using a macro or template in nearly every of my C++-Projects to get rid of it:
template<class T>
inline void safeDelete (T*& p) {
delete p;
p = NULL;
}
Keep in mind this isn’t thread-safe.
I don’t think this is safe. Shouldn’t you check if the pointer is null before you delete it? This way you won’t cause a crash by accidently calling SafeDelete twice.Eg:template<class T>inline void safeDelete (T*& p) { if ( p != NULL ) { delete p; p = NULL; }}
Campbell, you can safely delete null pointer without any crashes