Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason why not to have a DELETE macro for C++

Are there any good reasons (except "macros are evil", maybe) NOT to use the following macros ?

#define DELETE( ptr ) \
if (ptr != NULL)      \
{                     \
    delete ptr;       \
    ptr = NULL;       \
}

#define DELETE_TABLE( ptr ) \
if (ptr != NULL)            \
{                           \
    delete[] ptr;           \
    ptr = NULL;             \
}
like image 680
moala Avatar asked Aug 12 '09 11:08

moala


People also ask

Why you shouldn't use macros?

Macros repeat poorly constructed code all over the place — so you really need to know what you are doing with your macros and test them thoroughly before deploying them everywhere, and you need to avoid jumping down a rabbit hole if you want to go and update them later.

Do you need to delete pointers in C?

No. The only exception to that would be if deltaTime was created with new and it was the responsibility of Update to return the memory (unlikely, and a poor design). like you would with any other pointer? Just because something is a pointer does not mean you should call delete .

Why would you use a macro instead of a function?

Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it's used. A function definition occurs only once regardless of how many times it's called.

Is it good to use macros in C++?

So, macros not only make names shorter, and infact typedefs and ref alias can also be used to make names shorter, but macros can also avoid runtime overheads. Macros happen way before runtime. Macros have been avoiding run time over heads way before CPP features such as move and template.


1 Answers

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.

like image 106
Goz Avatar answered Oct 13 '22 18:10

Goz