How to make a pointer to a reference

In my previous post, I complained that one cannot make a reassignable reference in C++. Corollary to this is that a reference can never be uninitialized, since it is only in the statement that declares the reference can the compiler discern your intent to assign it rather than assign to the thing it is supposed to point to. I will not try to justify why this is logically the case since I think it’s stupid, but so it is.

That means that the concept of a “pointer to a reference” is vacuous, since a reference isn’t a thing, but merely a name for something else. If you wanted to point to one, you could just point to its referent (and you have to). An abstract “pointer to a reference type” can’t exist because then the thing it points to might be an uninitialized reference. For the same reason, you can’t have a reference to a reference.

Yet you can create a pointer to a reference by using a class:

struct int_ref
  int &x;
  int_ref(int &i): x(i) {}

int main(void)
  int_ref *irp;
  int i = 1;
  int_ref a(i); // Creates an int_ref initialized to i
  irp = &a; // irp is now a pointer to a reference!
  i = 2; // irp->x == 2 now
  int j = 3;
  int_ref b(j);
  irp = &b;
  i = 1; // irp->x == 3 still!
  // Really insidious
    int k = 4;
    irp = new int_ref(k);
  // Can you guess what irp->x is now?

Okay, the first part is just sort of cute: I can reassign a pointer to something that is effectively a reference. But the last part really breaks the language: you see, the variable k is supposed to go “out of scope” when the braces end: its name should be destroyed. If it doesn’t exist, how can I refer to it by name?

I also just asked this question on Stack Overflow.

This entry was posted in C++, Computers, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s