A reference is nothing more or less than a pointer in disguise. It is basically a C++ way of omitting adding the dereference operators when dereferencing a pointer.
From a language lawyer perspective, references may not be the same a pointers, but for all practical purposes, they are. Take for instance the assertion that references cannot be null, this is one of the arguments that people have used to advocate the use of references over pointers. However, while the language definition may disallow this, it is very easy to produce a null reference:
int& toReference(int* a) {
return *a;
}
What happens when you pass a null pointer to toReference()
? It will return a null reference. It won't technically dereference the pointer, because toReference()
has no interest in the value behind the pointer. To avoid returning a null reference, the compiler would have to specifically insert code to check whether the pointer is null, and abort the program, which would be a waste of CPU time. You get the segfault the moment you try to access the data behind the returned reference, no sooner.
Now, should you use references in your code?
As I said above references are pointers in disguise, and that disguise can be harmful. For instance, if you see a call like the following in C, you can be certain that bar
is not modified:
foo(bar);
In C++ you cannot be certain until you have checked whether the function definition contains a &
. This is bad. Even worse: imagine you are using a function declared like this:
void foo(int a);
Now, if someone decided, he needed a
to be an in/out parameter, and changed the definition into
void foo(int& a);
there would be absolutely no warning that the call foo(bar)
would now silently modify the value of bar
, i. e. the developer of foo()
can break essential assumptions in unrelated places. The only way to avoid such nasty surprises, is to ban the use of non-const references from function arguments. You may use const-references when you want to stick to pass by value semantics and want to avoid the overhead of copying, but use pointers if you intent to modify.