Interesting C++ Construct: Reference to Pointer

It looks like this:

type *p;
type *&r = p;

r here is a reference to the pointer p. In other words, it works just like the pointer itself, but if you decide to change it, p will change accordingly. r is now just a nickname for p, they are the same object in memory. References can also be used to allow functions to modify their arguments, avoiding the awkward pointer-to-pointer (type **p) construct. Here’s an example:

void eat_p(int *p)
{
p = new int[100];
}

void eat_rp(int *&p)
{
p = new int[100];
}

int main()
{
int *stuff = NULL;

eat_p(stuff);
/*
this will leak memory, as the function allocates memory to the local copy of p, and stuff in main() remains pointing to NULL. As soon as eat_p() returns, the memory is lost, as nothing points to it
*/

assert(stuff == NULL);

eat_rp(stuff);
/*
this will work as expected, stuff now points to allocated memory
*/

assert(stuff != NULL);

return 0;
}

Note that references exist only in C++, C supports no such thing.

Comments are closed.

%d bloggers like this: