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

后端 未结 20 2260
有刺的猬
有刺的猬 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:32

    One thing you have to consider is what happens if some caller DOES misuse your API. In the case of passing NULL pointers, the result is an obvious crash, so it's OK not to check. Any misuse will be readily apparent to the calling code's developer.

    The infamous glibc debacle is another thing entirely. The misuse resulted in actually useful behavior for the caller, and the API stayed that way for decades. Then they changed it.

    In this case, the API developers' should have checked values with an assert or some similar mechanism. But you can't go back in time to correct an error. The wailing and gnashing of teeth were inevitable. Read all about it here.

提交回复
热议问题