There is no cast required.
int* p = nullptr;
int& i = *p;
I just put used cast syntax to avoid an additional line of code, the
actual conversion is implicit.
IMHO, your example is still contrived, and semantically the error is at
the point where you've dereferenced a null pointer, as opposed to using
the reference later. But more importantly, your example abandons the
specific context in which my statement was made.
My comment was strictly about the use of a null _explicitly_ as a
parameter. You seem to have taken that as an opening to infer all sorts
of other things that I never wrote, nor never intended anyone to infer.
There's no explicitness in the getting around it. It can happen in
perfectly good-looking code. Thinking a reference is anything different
from syntactic sugar around a pointer *is* misinformed.
Whatever. Personally, I find that reference parameters in C++ help a lot
in documenting what is expected of the caller.
[...]
void use_it(T* p)
{
T t(...);
if (t == *p)
...
}
Clearly, if p is NULL, then operator== gets an invalid reference.
Again, semantically it's my opinion that the error occurs at the point of
dereference. That is, "*p" is invalid itself.
Does the use of a reference parameter prevent that? No, I never meant to
imply that it did. But the fact is that the null dereference would be an
error even without the reference parameter. That is, it's not even
related to the use of the reference parameter.
All that the use of the reference parameter does is change when the null
pointer causes the error. But semantically, the error occurred outside
the function using the reference parameter, when the null pointer was
dereferenced.
Pete