Why can const char* const & = “hello” compile?

  • A+
Category:Languages

I am reading a code snippet from a book and find this:

const char* const & a = "hello"; //can compile  const char*& a = "hello"; //cannot 

All I know is that when initializing a reference, the array to pointer conversion would not take place.

const char* const &, a reference to a const pointer, the pointer points to const char.

const char*&, a reference to a pointer, the pointer points to const char.

So why does adding an extra const, indicating that the pointer is a const, allow it to compile?

 


It's essentially adhering to this formula

T const & a = something_convertible_to_T; 

Where T is const char*. In the first case, a temporary pointer can be materialized, assigned the address of the literal, and then have itself bound to the reference. In the second case, since the lvalue reference isn't const, it can't happen. Another example of more of the same

const char* && a = "hello"; // rvalue ref makes a no into a yes. 

Now the temporary pointer is bound to an rvalue reference.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: