On 20 Kwi, 06:38, Pavel Minaev <int...@gmail.com> wrote:
To summarize: there's no such thing as a null reference, since
dereferencing a null pointer is U.B., and that's the only way to
obtain such a reference; however, most existing implementations do not
perform any checks, so you can get a "null reference" in a particular
implementation in practice (which is a possibility covered by saying
that it's U.B.).
If there is a possibility that someone will use null pointer on
your function taking reference, you should handle this. For example:
void function(MyClass& obj) {
assert (&obj != nullptr);
obj.method();
}
No, please don't do that. There is no possibility because anyone would
pass a "null reference" to such a function, because even if he does,
the mistake is already at the point of dereference (i.e. operator*),
and not at the call.
Okay, my bad. This idea was based on implementations I used, not on
standard. What I wanted to say was that a reference is not in some
magical way always referencing to an object and that the programmer
should now this.
I personally do not use such assert, mainly because I do not use
references to pass arguments in all cases. I think that the real
problem here is that the new programmers are told to use references
to pass arguments because it is safer. This is IMO totaly untrue
(or just on implementations I used). Passing null pointer to a
function (wich is documented not to accept null pointers)
and dereferencing null pointer to pass it by reference are both
errors done by programmer using the function. However in the
first case the function can check if the argument is correct
and in the second (w.r.t. standrad) it cannot.
So in the end passing by reference is no way to assure that
the argument is a valid object. Passing by reference is
a convenient way for passing stack allocated objects and
(with const reference) temporary objects. It is the only
way to implement copy constructor. However for heap allocated
objects passing by reference does not add anything.
argument passing mechanisms for stack and dynamic objects.
[ comp.lang.c++.moderated. First time posters: Do this! ]