const&

What does const& in following code mean?

1
2
3
const char*const & p ="!!!!";
        cout<<*p<<endl;
        cout<<p<<endl;

output
!
!!!!
The 'p' is a reference to constant pointer to constant character.

The purpose of the reference is not clear.
const char* const& p ="!!!!";

Reading the above from right to left:

p is a variable
p is a reference variable
p is a const reference variable
p is a const reference to pointer variable (NOT pointer to a reference)
p is a const reference to pointer variable to type char
p is a const reference to pointer variable to type const char - this implies that the value that is pointed to i.e "!!!!" can’t be changed, and p can’t be changed to point to anything else.

Now, in a similar vein to your earlier post (http://www.cplusplus.com/forum/beginner/202189/), "!!!!" is also a r-value and for the same reasons as in that post we'll need the const qualification to bind the r-value to the reference, hence the bit const& p

And when you de-reference p, cout<<*p as a const ref to pointer variable to type const char it prints the first char i.e. '!' while cout<<p of course prints the entire r-value of the assignment

edit: if you search 'references to pointers' there'll be some examples and uses but it seems to me a particularly arcane corner of C++ but maybe there is something more substantial someone can point out
Last edited on
Topic archived. No new replies allowed.