[ACCEPTED]-Reference pointing to a Null-object-null
I was surprised that no one talked about 12 when reference can point to a null object
That's 11 because it can't, in a correct program.
Your 10 function that dereferences a nullpointer 9 has Undefined Behavior. The compiler is allowed to emit code 8 that, for example, causes a crash at that 7 point.
However, one possible effect of UB 6 is that the code does what one thought it 5 would do. So null-references can occur. I 4 have never encountered one, but if you do, then 3 it means that there is a serious logic error 2 in the code.
All uses of the null-object-reference function you show, are logic errors.
You'd better grep up those uses 1 and fix things. ;-)
Cheers & hth.,
I was surprised that no one talked about 16 when reference can point to a null object.
(i) How 15 is it possible to do *nullPtr - Is is it 14 because nullPtr is a static object, which 13 is allocated memory on the heap and hence 12 it is guarenteed to have some space and 11 address allocated for deref?
It's not. You're 10 dereferencing a null pointer, which is invoking 9 undefined behaviour.
(ii) Since we are returning 8 const reference to obj, does compiler create 7 a temporary object (to some kind of nullObj??) or 6 Will the const reference act as an alias 5 to nullPtr itself?
No. The compiler, at 4 this stage, is allowed to produce nasal 3 daemons or a black hole. If you're very lucky, you'll 2 get a segmentation fault or some other kind 1 of access violation.
DO NOT DO THIS
(i) How is it possible to do *nullPtr - Is 16 is it because nullPtr is a static object, which 15 is allocated memory on the heap and hence 14 it is guarenteed to have some space and 13 address allocated for deref?
No, it's because 12
nullPtr is a pointer initialized to NULL, it's 11 not an object at all.
(ii) Since we are returning 10 const reference to obj, does compiler 9 create a temporary object (to some kind 8 of nullObj??) or Will the const reference act 7 as an alias to nullPtr itself?
It will be 6 an alias to an object located at memory 5 address NULL. I.e.: when you actually access 4 any of the members of this reference object 3 - you'll get whatever (usually access violation, if 2 the system is smart enough, but it can really 1 be anything, the behavior is undefind).
More Related questions