Re: STL Vector - pass by reference?
Ben Voigt [C++ MVP] wrote:
"Bo Persson" <bop@gmb.dk> wrote in message
news:5ibbgaF3op5viU1@mid.individual.net...
If someone passes an invalid reference to my functions, that is a bug in
their code, not my problem. If someone passes a null pointer, I must
handle that.
If someone passes a null or invalid pointer to my function, when the
function documentation forbids it, that is also a bug in their code.
Let's leave aside invalid pointers or references (e.g. to deleted objects or
uninitialised ones), because the mere copying of such singular values leads
to UB.
Then, there remains a function taking a pointer vs one taking a reference.
Creating an invalid reference is illegal anyway, so passing it to a
function is straight out. This means that even without looking at any
documentation I know that the reference can't be null.
There is no difference between pointers and references in this respect.
A reference is just syntactic sugar for a pointer.
It gives a different message to the reader. A pointer can be null, a
reference can't. The behaviour of a function when called with a null
pointer needs to be documented, even if it's just "Don't do it!". No such
requirement with a reference, all requirements are implicitly given by the
language.
Of course, the generated binary code is typically the same, but that's a
different issue.
Uli