Checking for null before pointer usage

后端 未结 13 2373
孤独总比滥情好
孤独总比滥情好 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:07

    This non-NULLness check can be avoided by using references instead of pointers. This way, the compiler ensures the parameter passed is not NULL. For example:

    void f(Param& param)
    {
        // "param" is a pointer that is guaranteed not to be NULL      
    }
    

    In this case, it is up to the client to do the checking. However, mostly the client situation will be like this:

    Param instance;
    f(instance);
    

    No non-NULLness checking is needed.

    When using with objects allocated on the heap, you can do the following:

    Param& instance = *new Param();
    f(*instance);
    

    Update: As user Crashworks remarks, it is still possible to make you program crash. However, when using references, it is the responsibility of the client to pass a valid reference, and as I show in the example, this is very easy to do.

提交回复
热议问题