Learning materials

Ref type vs pointer type

On this page

Difference

  • A ref variable cannot be re-assigned
  • A ref variable cannot be empty or undefined, not flexible
  • Ref type is easier to use with no ref/deref operations
  • Ref is safer to use
  • Pointer is more powerful and allows many algorithms
  • Array is also a pointer
  • New and delete only work with pointers

Pass-by-ref vs Pass-by-pointer

  • Both allow modification of the actual parameter
  • Pass by ref has simpler syntax
  • Pass by pointer allows more complicated logic
// swap pointer version
// called like swap(&a, &b);
void swap(int * ptr1, int * ptr2) {
  int tmp = *ptr1;
  *ptr1 = *ptr2;
  *ptr2 = tmp;
}

// swap ref version
// cleaner syntax
// called like swap(a, b);
void swap(int & ref1, int & ref2) {
  int tmp = ref1;
  ref1 = ref2;
  ref2 = tmp;
}