Meaning of *& and **& in C++
First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.
void foo(int*& x, int**& y) {
// modifying x or y here will modify a or b in main
}
int main() {
int val = 42;
int *a = &val;
int **b = &a;
foo(a, b);
return 0;
}
That's passing a pointer by reference rather than by value. This for example allows altering the pointer (not the pointed-to object) in the function is such way that the calling code sees the change.
Compare:
void nochange( int* pointer ) //passed by value
{
pointer++; // change will be discarded once function returns
}
void change( int*& pointer ) //passed by reference
{
pointer++; // change will persist when function returns
}
That is taking the parameter by reference. So in the first case you are taking a pointer parameter by reference so whatever modification you do to the value of the pointer is reflected outside the function. Second is the simlilar to first one with the only difference being that it is a double pointer. See this example:
void pass_by_value(int* p)
{
//Allocate memory for int and store the address in p
p = new int;
}
void pass_by_reference(int*& p)
{
p = new int;
}
int main()
{
int* p1 = NULL;
int* p2 = NULL;
pass_by_value(p1); //p1 will still be NULL after this call
pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory
return 0;
}