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?
I was surprised that no one talked about when reference can point to a null object
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.,
I was surprised that no one talked about when reference can point to a null object.
Never.
(i) 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 guarenteed to have some space and address allocated for deref?
It's not. You're dereferencing a null pointer, which is invoking undefined behaviour.
(ii) 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?
No. The compiler, at this stage, is allowed to produce nasal daemons or a black hole. If you're very lucky, you'll get a segmentation fault or some other kind of access violation.
DO NOT DO THIS
(i) 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 guarenteed to
have some space and address allocated
for deref?
No, it's because nullPtr
is a pointer initialized to NULL, it's not an object at all.
(ii) 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?
It will be an alias to an object located at memory address NULL. I.e.: when you actually access any of the members of this reference object - you'll get whatever (usually access violation, if the system is smart enough, but it can really be anything, the behavior is undefind).