Posted in C++, C++/CLI on June 7, 2006 |
7 Comments »
This is an often asked question in newsgroups and forums.
A lot of people do this :-
if(p)
delete p;
The assumption is that, if they do not check for NULL, delete will result in a crash or in random behavior. This is not correct. C++ guarantees that a delete will do nothing if the pointer is NULL. See entry [16.8] on http://www.parashift.com/c++-faq-lite/freestore-mgmt.html.
It’s the same for managed code. You do not have to check for nullptr. Consider the following code :
int main()
{
R^ r = nullptr;
delete r;
}
The generated IL checks to see if the object supports IDisposable, and if so, it calls Dispose on it. And if your object implements IDisposable, which in C++/CLI means that you have a destructor, there will be a Dispose generated for you. Note that, Dispose will not be called if the object is a nullptr.
So, in summary, irrespective of whether you are using native objects or CLI objects, you *can* delete a NULL pointer.
Read Full Post »