Pointers vs References
- References can’t be
NULL, they are safer to use.
- A pointer can be re-assigned while reference cannot, and must be assigned at initialization only.
- A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.
- For function parameter: use mutable references for non-optional mutable parameters and remove the
== nullptrchecks; otherwise use pointer.
Pointer variables store memory locations. When dealing with pointers, you use the
* symbol in two distinct but related ways:
- As part of a type specifier (such as in
int* p), meaning
pis a pointer to an
- As the dereference operator (such as in
*p), meaning use the value a pointer points to.
int x = 42; int* p = &x; std::cout << "p points to memory location " << p << " which contains " << *p;
Reference variables are defined using the & symbol, but don't confuse that usage with the address-of operator. You use the & symbol in two completely unrelated ways:
As part of a type specifier (such as int& r), meaning r is another name for some int object. As the address-of operator (such as &r), meaning get the address of a variable. Here's an example of both kinds of &:
int x = 42; int& r = x; // r is another name for x assert(r == x); // they have the same value assert(&r == &x); // they have the same address!
Notice that you can treat r just like x, including taking its address with the & operator. Once it's defined, its behavior and notation are indistinguishable from the original variable.3
Unlike pointers, references can never be moved ("reseated") to refer to a different object. In the following code, pointer p starts out pointing at x, then switches to point to y:
int x = 42; int* p = &x; // p points at x int y = 1138; p = &y; // now p points at y
In contrast to pointers, the following code uses references. Reference r always refers to x. The assignment r = y assigns the value contained in y to the variable called r, another name for x:
int x = 42; // x == 42 int& r = x; // x == 42 &r == &x int y = 1138; // x == 42 &r == &x y == 1138 r = y; // x == 1138 &r == &x y == 1138