Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a pointer to a reference?

I was reading C++ Primer and I noticed that there's a statement says:

Because references are not objects, they don't have addresses. Hence, we may not define a pointer to a reference.

But I just wrote an example code and shows that it's possible to create a pointer to a reference (the d variable).

The code is posted below:

#include <iostream>
using namespace std;

int main(){
   int a = 1024;

   int &b = a; // a reference to int
   int &c = b; // a reference to another reference
   int *d = &b; // a pointer to a reference
   int *(&e) = d; // a reference to a pointer 

   a = 100;
   cout << b << endl;
   cout << c << endl;
   cout << *d << endl;
   cout << *e << endl;
}

So, anything wrong with my test? Or the statement in C++ Primer is wrong?

I'm reading C++ Primerfifth edition. The statement is in page 52, 2.3.2.

like image 426
yegle Avatar asked Jun 13 '13 21:06

yegle


2 Answers

The quote is right, since you're making a pointer pointing to the original object, not its reference. The code below shows this fact:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int a = 0;
  // two references referring to same object
  int& ref1_a = a;
  int& ref2_a = a;
  // creating a different pointer for each reference
  int* ptr_to_ref1 = &ref1_a;
  int* ptr_to_ref2 = &ref2_a;

  printf("org: %p 1: %p 2: %p\n", &a, ptr_to_ref1, ptr_to_ref2);

  return 0;
}

output:

org: 0x7fff083c917c 1: 0x7fff083c917c 2: 0x7fff083c917c

If you said you're able to make a pointer for reference, then the above output should be different.

like image 76
keelar Avatar answered Oct 14 '22 18:10

keelar


No, you can't make a pointer to a reference. If you use the address-of operator & on it you get the address of the object you're referencing, not the reference itself.

like image 20
Mark Ransom Avatar answered Oct 14 '22 17:10

Mark Ransom