Pointers and references are conceptually the same, although there are subtle differences between them. The most remarkable of them (and probably, the least important, although more comfortable and readable), is that the references do not require the arrow syntax ->
needed by the pointers to access members (in the case that an object ( class
) or registration ( struct
) is targeted), or access operator *
, but use the same name to access the value, and operator .
, which would be used with the same object, to access the members.
References were invented, in fact, to avoid having to use pointers when performing a step by reference (and for returns by reference), that is, when you want changes made within the function called to the object pointed impact on the calling function.
This code is relatively complex for what you really want to get:
unsigned long x = 4;
void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
While the version with references is much more readable:
unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
So, as for the specific question, I certainly think that the use of references is the most appropriate. The underlying question is: can references be always used instead of pointers? The answer is no, because the references carry several inherent limitations to its operation:
-
References can not be initialized to NULL or nullptr. Moreover, they can not even be created without being initialized. And once initialized, you can not change the object or value they point to.
-
Pointer arithmetic can not be used with a reference. For example, you can not traverse an object vector with a reference, because you can not change the object it points to once it has been created.
Thus, the following code can not be written with a reference:
Persona * p = personas;
for(; ( p - personas ) < MaxPersonas; ++p) {
cout << p->getNombre() << endl;
}
Hence the "golden rules" that appear in the other answer: if you need to point to more than one object, or you need to indicate that you do not point to anything (NULL value), or you need to use pointer arithmetic, then you can not Use references. When you can use them, however, do not hesitate to do so, because they are much more readable thanks to their syntax.
I hope I have helped you.