Ref type vs pointer type

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

 1// swap pointer version
 2// called like swap(&a, &b);
 3void swap(int * ptr1, int * ptr2) {
 4  int tmp = *ptr1;
 5  *ptr1 = *ptr2;
 6  *ptr2 = tmp;
 7}
 8
 9// swap ref version
10// cleaner syntax
11// called like swap(a, b);
12void swap(int & ref1, int & ref2) {
13  int tmp = ref1;
14  ref1 = ref2;
15  ref2 = tmp;
16}