#1Pointers vs references

A pointer is an object that holds an address of another object. A reference is an alias (not an object) that references another object. This means:

  • Operations that you perform on a pointer, apply to the pointer itself, not to the object it points to (a pointer is an object). For example, assigning a value to a pointer changes the object that this pointer points to, but doesn't assign new value to the pointed object.
  • Operations that you perform on a reference, apply to the referenced object and not to the reference itself (a reference is not an object). For example, assigning a value to a reference assigns a new value to the referenced object but doesn't change the object that the reference references to.
  • The distinction between pointers and references may help compilers apply optimizations in certain situations when using references. The same is true for pointers but requires a more careful analysis by the compiler to not break the code.

Since references are not objects, they are subject to certain restrictions related to their initialization:

  • References must be initialized at definition. Pointers might be left uninitialized.
  • Because a reference is not an object, it cannot be changed to alias another object after initialization.
  • References cannot be null unlike pointers. In practice however, you can initialize a reference from a null pointer which is undefined behavior, but as with any other undefined behavior it happens to somehow work. You cannot do much with such reference and it'll cost you a crash of your program at some point.

Sample code

References

  1. C++ Primer, Fifth Edition, chapter 2.3.1. References
  2. C++ Primer, Fifth Edition, chapter 2.3.2. Pointers
  3. The Design and Evolution of C++, chapter 3.7. References

All (4 shorts)