I don't believe you have to do anything at all. If the if statement is better or not, we can't really say. The best way is to use a profiler, but that would be a little overkill, wouldn't it?
Unless you're deleting millions of pointers/second, 1 more or less instruction will be completely unnoticable.
>> If the if statement is better or not, we can't really say.
We can discuss it and come to the best logical conclusion possible. My logic tells me it is better to leave it out. Apparently Stroustrup agrees, so I would take it out. Definitely not a big deal but why not make the best decision possible?
If you don't care about the optimization, then use the clearer version, which again is the one without the if, IMO.
Why not just use a macro like
Code:#define SAFE_DELETE(p) { delete p; p = NULL; }
Because macros do not respect scope, are not type-safe, can be used on a void pointer, etc etc.
Macros like yours also will also result in a compilation error with code like;
although that's a property of your macro, which can be addressed by;Code:if (some_condition) SAFE_DELETE(some_pointer); else something_else();
Code:#define SAFE_DELETE(p) do {delete p; p = NULL;} while (0)
I don't like the name SAFE_DELETE. An individual call to SAFE_DELETE is no safer than just calling delete. After all, that's the first thing SAFE_DELETE does anyway.
I would take a lesson from Delphi which has FreeAndNil, calling this DELETE_AND_NULL, to properly say what it does.
Then I would proclaim that it is so ugly and pointless that I would throw it away and just use delete instead. I would only NULL the pointer when I actually need to, which is almost never if you properly use RAII.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"