📅 2016-Dec-28 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, pointer, reference ⬩ 📚 Archive
Reference to pointer is a useful construct to be aware of in C++. As you might already know, the C++ language allows you to take a reference to any object that is not a temporary. You can take a const reference to any object, including a temporary. So what is special about reference to a pointer?
A common construct in C++ is to receive a pointer to a pointer as input argument to a function. This is typically used to allocate a primitive or an object inside the function. The allocated primitive or object will be available in the caller after the function is called and done with. This idiom is common with C programmers who have moved to C++. It is such code that becomes a lot cleaner and easier to write and read if a reference to pointer is used as input argument to function. As a bonus, since it is a reference it has to always refer to a pointer that actually exists.
The code example below shows the difference between pointer to pointer and reference to pointer:
// Example that shows difference between pointer-to-pointer
// and reference-to-pointer.
#include <cstdio>
void func_ptr(int **x)
{new int;
*x = 100;
**x =
}
void func_ref(int * &x)
{new int;
x = 99;
*x =
}
int main()
{// Pointer-to-pointer
{int *xp = nullptr;
func_ptr(&xp);"%d\n", *xp);
printf(delete xp;
}
// Reference-to-pointer
{int *xp = nullptr;
func_ref(xp);"%d\n", *xp);
printf(delete xp;
}
return 0;
}
Note how reference-to-pointer is cleaner to understand both at the caller location and inside callee.