r...@zedat.fu-berlin.de (Stefan Ram) writes:
> When asked for the difference between pointers and references
> some say that references cannot be null. I know what this is
> /intended/ to mean, but the wording might not correctly convey
> this for readers who do not yet known this. For an example how
> this can be (mis)understood, I show the following program that
> has a reference that /is/ null!
>
> #include <iostream>
> #include <ostream>
>
> struct V { int i; };
>
> void f( V * & q ){ ::std::cout << q->i << '\n'; }
>
> int main(){ V * p = nullptr; f( p ); }
>
> »q« is a reference, and it /is/ null!
No. q is a reference to a pointer, and the pointer's value is nullptr.
I.e., q refers to something that exists in a valid state (the variable p
of main). In the body of f(), writing "q = ...any pointer to a V..." is
perfectly ok. What you do instead is: accessing the value pointed to by
the pointer referenced by q. The former part (accessing the value
pointed to...) is faulty, the latter (the pointer referenced by q) is
valid.
You can still create an invalid reference:
V * p = nullptr;
V & q = *p;
but imho the initialization has undefined behavior because you
dereference an invalid pointer (even though you do not really
dereference it).
-- Alain.