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:
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 :).
Yes it is safe. There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.
@Omega delete pointer; pointer = nullptr. just deletes the pointer. setting it to null after deleting is fine. Setting null to a pointer is not same as deleting.
Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
In this case delete operation on one pointer would make only that pointer NULL (if delete was making pointer NULL) and the other pointer would be non-NULL and pointing to memory location which is free. The solution for this should have been that user should delete all pointers pointing to same location.
Yes, I would not recommended doing it.
The reason is that the extra setting to null will only help in very limited contexts. If you are in a destructor, the pointer itself will not exist right after the destructor execution, which means that whether it is null or not does not matter.
If the pointer was copied, setting p
to null will not set the rest of the pointers, and you can then hit the same problems with the extra issue that you will be expecting to find deleted pointers being null, and it won't make sense how your pointer became non-zero and yet the object is not there....
Additionally it might hide other errors, like for example if your application is trying to delete a pointer many times, by setting the pointer to null, the effect is that the second delete will be converted to a no-op, and while the application will not crash the error in the logic is still there (consider that a later edit accesses the pointer right before the delete
that is not failing... how can that fail?
I recommend doing so.
Personally, I use an inline function that takes the pointer as a reference and sets it to NULL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With