Is a C++ reference to an object analogous to a double pointer in C?

Viewed 127

I am reading "Accelerated C++" by Koenig. In chapter 5, Koenig defines a function which has a reference to a vector parameter. In the function body, a new vector is created and assigned to the parameter.

Is a reference to an object analogous to a double pointer in C?

I am imagining a local variable which is a pointer to a data structure on the heap (a vector in this case). The address of this variable (a double pointer) is passed to a function and, in the function body, is dereferenced and assigned the address of a new data structure on the heap (in this case, a new vector).

I realize references have different properties than pointers and that references are not necessarily implemented as pointers. However, is the above a reasonable way to think about things?

1 Answers

A pointer is always a separate value, that is in the case of:

int x = 1;
int *y = &x;

There are two values here, x and y. These have different addresses such that:

&x != &y

In the case of references it's just a code alias, not an actual separate thing, so:

int x = 1;
int &y = x;

Where now you have two names for exactly the same thing:

&x == &y

As x and y are from that point forward effectively interchangeable.

Remember that pointers must be de-referenced to be used. A reference requires no such special handling.

Where there's similarity is that a pointer can be used to manipulate a shared value, or a pointer-pointer to manipulate a pointer, but there is a level of indirection that makes it different.

In C where you don't have references you use pointers instead, so you have functions like this:

void mutate(int* v);

Where that's a pointer meaning "mutable value", though in C++ it looks like:

void mutate(int& v);
Related