Pointers and references look very different (pointers use
->, while references use
.), but they seem to have the same function: both can be used to indirectly point to another object. So when should you use pointers vs. references?
The most important thing you should always remember is that, reference can never be assigned
NULLdirectly. A reference has always to refer to an object. Therefore, if you need a variable that needs to point to nothing sometimes, then this variable should be declared as a pointer, not a reference. The fact that reference should always refer to an object makes the program more effective, because it doesn’t need to be tested
A pointer can be re-assigned to another object, but a reference cannot. A reference must be assigned at initialization.
A pointer can points to a 2nd pointer, which points to a 3rd pointer, … This offers extra levels of indirection. Whereas a reference only offers one level of indirection.
Pointers can iterate over an array, you can use
++to go to the next item, and
+nto go to the (n+1)th element. This is no matter what size the object is that the pointer points to.
The last situation is that when you need to overload an operator, you should use references rather than pointers. A typical overloaded operator is
, by which an object should be returned. For example
vector<int> v(10); v = 10;
If the operator
returns a pointer, the last line would be
*v = 10;
This would make
vlook like a vector of pointers.
Also, a pointer has its own memory address and size on the stack, whereas a reference shares the same memory address with the original variable. So it is safe to think of a reference as another name for the same variable. This difference is important, but I don’t think it is a reason when choosing references vs pointers.