Searching something on SO, I stumbled across this question and one of the comments to the most voted answer (the fifth comment to that most voted answer) suggests that delete p; p = NULL;
is an antipattern. I must confess that I happen to use it quite often paring it sometimes\most of the times with the check if (NULL != p)
. The Man himself seems to suggest it (please see the destroy()
function example) so I'm really confused to why it might be such a dreaded thing to be considered an antipattern. I use it for the following reasons:
- when I'm releasing a resource I also want to kind of invalidate it for further usage and NULL is the right tool to say a pointer is invalid
- I don't want to leave behind dangling pointers
- I want to avoid double\multiple free bugs - deleting a NULL pointer is like a nop but deleting a dangling pointer is like "shooting yourself in the foot"
Please note that I'm not asking the question in the context of the "this" pointer and let's assume we don't live in a perfect C++ world and that legacy code does exist and it has to be maintained, so please do not suggest any kind of smart pointer :).