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?
const char* means pointer to constant character. char const* means exactly the same as 1. (you probably were going for char* const , which is constant pointer to a character.)
const char* is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of '*'(asterik) is also same. 2. char *const ptr : This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by ptr.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With