Posted By: System | Oct 25th, 2007 @ 3:58 AM
page 1 of 1
Comments: 2 | Views: 2109
I was reading through a text book today and noticed that the author had used #define to create a macro for deleting objects.

#define SAFE_DELETE( p )    { if( p ) { delete ( p );     ( p ) = NULL; } }

So, I thought this would be a perfect opportunity to replace this macro with a template inline function.

template<typename T>
inline void safeDelete(const T&p)
    {
    if (p)
        {
        delete (p);
        }
    }

However, it then dawned on me that if I was to use this function - it wouldnt be possible to pass in a pointer to an object? Wouldnt it have to be a const reference?

For example if I had a pointer to an object g_engine of type Engine which I now wanted to delete could I call:

safeDelete <Engine> (g_engine);

I wouldnt of thought so because you would get a conversion error, wouldnt you?

Could this of been why the author used a #define macro or is there a way to do this using a inline function? Also, if there is - are #define macros pretty much dead now - or are there still situations where you would prefer to use them over inline functions?



Sven Groot
Sven Groot
My name has 9 letters. Coincidence? I think not...

You can pass it a pointer. If you do, the function will resolve to "safeDelete(const Foo *&p)". You'd end up with a const reference to a pointer (note that your call won't work since the type argument needs to be Engine* not Engine, see also below). However it wouldn't work, because, being a const reference, you can't do p = NULL at the end. Remove the const and you're fine. Personally I would define it as "template<typename T> inline void safeDelete(T *&p)" to enforce pointer arguments.

Second, remove the if(p) check! C++ guarantees that using delete on a NULL pointer does nothing. Calling delete on a NULL pointer is completely safe. See also here.

Last, you don't need to specify the type argument in the call. If you just call safeDelete(g_engine) it already works fine, it'll automatically deduce the template argument to be Engine*.

So this is what you'd end up with:

template<typename T>
inline void safeDelete(T *&p)
{
   delete p;
   p = NULL;
}

Ah right I see, that makes sense. Thanks for clearing that up for me.
page 1 of 1
Comments: 2 | Views: 2109
Microsoft Communities