Checking for null before pointer usage

后端 未结 13 2569
孤独总比滥情好
孤独总比滥情好 2021-02-20 09:32

Most people use pointers like this...

if ( p != NULL ) {
  DoWhateverWithP();
}

However, if the pointer is null for whatever reason, the functi

13条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 10:00

    I think it is better to check for null. Although, you can cut down on the amount of checks you need to make.

    For most cases I prefer a simple guard clause at the top of a function:

    if (p == NULL) return;
    

    That said, I typically only put the check on functions that are publicly exposed.

    However, when the null pointer in unexpected I will throw an exception. (There are some functions it doesn't make any sense to call with null, and the consumer should be responsible enough to use it right.)

    Constructor initialization can be used as an alternative to checking for null all the time. This is especially useful when the class contains a collection. The collection can be used throughout the class without checking whether it has been initialized.

提交回复
热议问题