2

Is there a way to accomplish what this block of code does in C++ without using a typedef?

typedef int* pointer;
int a = 3;
int* ap = &a;
const pointer& apr = ap;
*apr = 4;

This won't do it:

int b = 3;
int* bp = &b; 
const int*& bpr = bp; 
*bpr = 4;

In fact, that second block won't compile, because the const makes bpr a reference to a read-only pointer, not a const reference to a read-write pointer. I was kinda hoping that parenthesis would save me:

const (int*)& bpr = bp; 

...but no luck there. So do I have to typedef the pointer type in order create a const reference to a read-write pointer?

Robz
  • 1,747
  • 5
  • 21
  • 35
  • You never *need* a typedef. – Ed S. Dec 01 '13 at 05:20
  • @EdS., I invite you to answer [this one](http://stackoverflow.com/questions/20308716/how-to-write-a-c-conversion-operator-returning-reference-to-array). Please do. – chris Dec 01 '13 at 05:21
  • @chris: Nice! Revised: *"You very rarely need a typedef"*. 10 years and I've just never found myself in that kind of situation. – Ed S. Dec 01 '13 at 05:22
  • @EdS., I have really vague memories of a SO post/comment about them being necessary for something, but there was no way I was going to remember where that was. All this time of that lingering in my memory and maybe this is what their example was. I mean I recently came across a typedef being necessary in order to make the name of the type an identifier, but that's just library design. Also, in terms of C, [this](http://stackoverflow.com/questions/3829522/is-typedef-ever-required-in-c) could be worth looking through. – chris Dec 01 '13 at 05:41
  • @chris a typedef is necessary if you want to declare a conversion operator to function pointer. – jrok Dec 26 '13 at 11:22

1 Answers1

11

Use the spiral rule:

int* const &bpr = bp; 

This is read as bpr is a reference to a constant pointer to an int.

For a sample, see here.

Thank you to dasblinkenlight for pointing out that the parentheses in the original answer were not required.

chris
  • 60,560
  • 13
  • 143
  • 205
  • I think parentheses are optional there ([link](http://coliru.stacked-crooked.com/)). – Sergey Kalinichenko Dec 01 '13 at 05:10
  • @dasblinkenlight, Good point, thank you. I'm too used to putting them there with references to arrays. – chris Dec 01 '13 at 05:11
  • thanks for the note about the spiral rule. is what you have there the same as making a const reference to a pointer to an int? – Robz Dec 01 '13 at 06:17
  • @Robz, There are no const references ([example](http://coliru.stacked-crooked.com/a/d246066ba246778d)), only references to const, so it's probably the same as what you imagine it as. – chris Dec 01 '13 at 06:23
  • ah, I see I've been thinking about this all wrong. now your answer makes sense. thanks! – Robz Dec 01 '13 at 06:29