Monday, February 23, 2009

Do NOT always check for NULL! (C++)

First of all, please note that this applies only to C++.

Do NOT check for NULL when allocating memory with new, since new will never return NULL! More information can be found here:
C++ FAQ Lite

As well, if you have:
int *x = new int;
...
if(x != NULL)
delete x;

That is bad! The language guarantees that if delete is used on a pointer that is NULL, nothing will happen. So instead of testing for NULL (and therefore slowing down your program needlessly), you should just do:
int *x = new int;
...
delete x; //Doesn't matter if it's NULL!

Author : Kevin Lam

0 nhận xét:

Post a Comment