I saw this discussion – Checking for a null object in C++ and I was surprised that no one talked about when reference can point to a null object. In our code, we use null objects routinely. There are functions as follows which return nullObj.
const Obj&
nullObj()
{
static obj* nullPtr = NULL;
return static_cast< const Obj&>(*nullPtr);
}
Actually, when I looked at the code again to bring this topic up, I had some questions on how the above code works:
-
How is it possible to do
*nullPtr– Is is it because nullPtr is a static object, which is allocated memory on the heap and hence it is guaranteed to have some space and -
Since we are returning const reference to obj, does compiler create a temporary object (to some kind of nullObj??) or Will the const reference act as an alias to nullPtr itself?
That’s because it can’t, in a correct program.
Your function that dereferences a nullpointer has Undefined Behavior. The compiler is allowed to emit code that, for example, causes a crash at that point.
However, one possible effect of UB is that the code does what one thought it would do. So null-references can occur. I have never encountered one, but if you do, then it means that there is a serious logic error in the code.
All uses of the null-object-reference function you show, are logic errors.
You’d better grep up those uses and fix things. 😉
Cheers & hth.,