quote:
Original post by Ratheous
Mine went something like this:
#define DeAlloc(OBJ) if(OBJ != NULL) delete OBJ; OBJ = NULL
I don't often use the macro any longer, I think it was more a safty net to correct sloppy coding on my part, and I'm trying to avoid that
First thing, just to repeat what Void already stated, you don't need to check for NULL, because delete NULL is defined to do nothing.
Second, as Void also stated, use delete to free from new, and delete[] to free from new[].
Now, in addition... You called your macro a safety net; possibly a misnomer, but let's go with that. So why do you want to avoid it? If you write a function that helps you write safer code,
GREAT!!! Maybe one day I'll buy a game that isn't already patched before it hits the shelves....
Really, "safety net" functions are good things. Some will argue that you lose performance. This may be true (and it may not; check with a profiler). In any case, coders would be much better off by writing code that FIRST works and SECOND gets optimized. (In all the threads on this forum, I haven't seen a SINGLE good, valid reason why you should optimize code before you get the code correct.) I'm a professional game developer and use such functions all the time. Saves typing, saves redundant code....
So my final point, then, is help in making your safety net functions better. First, if you're using C++, I HIGHLY recommend moving from preprocessor defines to inline and/or templatized functions. For your safe delete, something like:
template <class T> void DeAlloc(T*& t){ delete t; t = NULL;}
While you don't need to check against NULL before calling delete, it may be beneficial to set the pointer to NULL if there is the possibility that the pointer might still be visible to the calling scope.
As for arrays, you could create a safe DeAllocArray() helper to work in a similar fashion, using delete[] instead of delete. Personally, I would go another route; try looking up auto_ptr in your favorite books/websites for something similar to what I use. auto_ptr isn't perfect nor complete, but a great start.
---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!
Edited by - mossmoss on October 18, 2000 9:40:11 AM