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
I am pro defensive programming.
Unless you can profile that these nullptr
checkings happen in a bottleneck of your application... (in such cases it is conceivable one should not do those pointers value tests at those points)
but all in all comparing an int
with 0
is really cheap an operation.
I think it is a shame to let potential crash bugs instead of consuming so little CPU.
so: Test your pointers against NULL!
I don't think it's the responsibility of the callee to deal with such things
If it doesn't take this responsibility it might create bad results, like dereferencing NULL
pointers. Problem is that it always implicitly takes this responsibility. That's why i prefer graceful handling.
Yes, you should check for null pointers. You don't want to crash an application because the developer messed something up.
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.
While in general I don't see the value in detecting NULL (why NULL and not some other invalid address?) for a public API I'd probably still do it simply because many C and C++ programmers expect such behavior.
In C++, if you don't want to accept NULL pointers, then don't take the chance: accept a reference instead.