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 andSince 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?