What does it mean to pass a pointer parameter by reference to a function?

When you pass by reference, it acts as an alias -- be it a normal object or a pointer.

To explain in detail, let's consider below declaration:

int i = 10, *pi = &i;

Now following are the different meanings of passing and using them in various functions:

void foo_pointer (int* p) // 1st (can pass `&i` and `pi`)
{ 
  *p = 0;  // modifies `i`
   p = nullptr; // no effect on `pi`
}
void foo_pointer_reference (int*& p) // 2nd  (can pass `pi`)
{ 
  *p = 0;  // modifies `i`
   p = nullptr; // modifies `pi`
}
void foo_const_pointer_reference (const int*& p) // 3rd (can pass `pi`)
{ 
  *p = 0;  // ERROR
   p = nullptr; // modifies `pi`
}
void foo_const_pointer_const_reference (const int* const& p) // 4th (can pass `&i` and `pi`)
{ 
  *p = 0;  // ERROR
   p = nullptr; // ERROR
}

From above examples, you can see that another use case of declaring T*& as a function parameter is that, it restricts only pointer passing to that function. i.e. in above case &i is not allowed to be passed to 2nd and 3rd functions. However pi can be passed to all the functions.


You can pass a pointer by reference if you want the function you call to change the pointer to point to something else. Other than that, I don't see any valid reason (but that is sometimes a valid reason).

Tags:

C++