In either C or C++, should I check pointer parameters against NULL/nullptr?

后端 未结 20 2321
有刺的猬
有刺的猬 2020-11-27 03:54

This question was inspired by this answer.

I\'ve always been of the philosophy that the callee is never responsible when the caller does something stupid, like passi

20条回答
  •  没有蜡笔的小新
    2020-11-27 04:48

    My philosophy is: Your users should be allowed to make mistakes, your programming team should not.

    What this means is that the only place you should check for invalid parameters including NULL, is in the top-level user interface. Everywhere the user can provide input to your code, you should check for errors, and handle them as gracefully as possible.

    Everywhere else, you should use ASSERTS to ensure the programmers are using the functions correctly.

    If you are writing an API, then only the top-level functions should catch and handle bad input. It is pointless to keep checking for a NULL pointer three or four levels deep into your call stack.

提交回复
热议问题