ptr-ref layering #reference to pointer

Update http://markgodwin.blogspot.sg/2009/08/c-reference-to-pointer.html is a detailed blog post

Background — I doubt you ever need to know these arcane data types, but these are at work whenever you specialize a class template using a pointer as the “T”.

int * ptr2int;
int * & ref2ptr = ptr2int; // ok

int **** ptr;
int ****& ref = ptr; // ok

Real Case in point from EffC++ : The default allocator of vector (and many containers) has a nested typedef for T* (called “pointer”) and a nested typedef for T& (called “reference”). Now if you instantiate a vector using a reference type as the “T”, you die, because

The pointer typedef won’t compile, because you can’t declare a pointer to a reference; [1]
The reference typedef won’t compile, because you can’t declare a reference to a reference.

However, You can have a ref to a pointer to a pointer to a pointer to a pointer….

[1] However, we often take address of a reference variable. See https://bintanvictor.wordpress.com/2012/04/04/convert-a-reference-variable-to-a-pointer-variable/

Now the rule on reference-pointer layering –

  • If you start with a nonref variable, you can add “pointer” layers over and over, but any “reference” layer must be the last layer.
  • In other words, once you “reference” anything, you can’t layer on top of it.
    • You can declare a variable “pointing to” anything, so long as there’s not already a reference layer
    • You can declare a variable “referencing” anything, so long as there’s not already a reference layer
    • Pointer-to-reference is illegal as a variable type, but you can take the address of a reference!

 

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s