Are there any good reasons (except \"macros are evil\", maybe) NOT to use the following macros ?
#define DELETE( ptr ) \\
i
Personally I prefer the following
template< class T > void SafeDelete( T*& pVal )
{
delete pVal;
pVal = NULL;
}
template< class T > void SafeDeleteArray( T*& pVal )
{
delete[] pVal;
pVal = NULL;
}
They compile down to EXACTLY the same code in the end.
There may be some odd way you can break the #define system but, personally (And this is probably going to get me groaned ;) I don't think its much of a problem.
deleting a null pointer does nothing, so no need to check whether the pointer is null before deletion. Nullifying the deleted pointer might still be needed (but not in every case).
Macros should be avoided as much as possible, because they are hard to debug, maintain, introduce possible side effects, they are not part of namespaces, etc.
deleting a pointer that was not dynamically allocated with new will still be a problem...
Yes, you should never call delete directly. Use shared_ptr,scoped_ptr,unique_ptr or whatever smart pointer you have in your project.
Because it is OK to delete a NULL(0)
pointer. The is no need to check if the pointer actually is NULL(0)
or not. If you want to set the pointer to NULL, after deleting, then you can overload the delete
operator globally with out using macros.
It seems that I was wrong about the second point:
If you want to set the pointer to NULL, after deleting, then you can overload the
delete
operator globally
The thing is that if you overload the global new
and delete
, you could have something like this:
void* operator new(size_t size)
{
void* ptr = malloc(size);
if(ptr != 0)
{
return ptr;
}
throw std::bad_alloc("Sorry, the allocation didn't go well!");
}
void operator delete(void* p)
{
free(p);
p = 0;
}
Now, if you set p = 0;
in the overloaded delete
, you are actually setting the local
one, but not the original p
. Basically, we are getting a copy of the pointer in the overloaded delete
.
Sorry, it was on the top of my head, I gave it a second thought now. Anyway, I would write template inline function to do the thing instead of writing EVIL MACROS :)
Use boost::shared_ptr<> instead.
http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm
The MACRO here provides some of the functionality you are probably looking for.