Consider the following piece of code
class Foo
{
public:
//...
bool valueFirstGet(int& value) const
{
if(this==nullptr)
{return 0;}
value=values[0];
return 1;
}
//...
private:
int* values;
size_t n_values;
};
int main()
{
Foo* obj=findObject("key");
int value;
if(!obj->valueFirstGet(value))
{printf("key does not exist\n");}
return 0;
}
findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.
EDIT:
Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?
EDIT 2:
What about a static wrapper?
Best Answer
The null-check in
valueFirstGet
can not yield true without there being undefined behavior in the program, because you must dereference a null-pointer (which causes UB) to let that test yield true. The nasty thing about undefined behavior is that any behavior is fully sanctioned and that behavior might change between compiler versions or even optimization levels without notice.The correct way to go about this is to have the check in the caller or in a helper method. If the
findObject
/valueFirstGet
calls are commonly paired with no further use for the object returned byfindObject
, you can even do something like this:The short-circuit behaviour of
&&
ensures thatvalueFirstGet
will only be called if the object could be found.