I can make pointer point to string literal, it will cast string literal to constant pointer, but reference to pointer can't assign string literal, for example:
const char *&text = "Hello, World\n";
There's an error, the compiler says I can't cast an array to pointer reference, I am curious about it, why it isn't it correct?
String literal as a Pointer String literals are stored just like arrays. The most important point to understand is that a string literal is a pointer to the first character of the array. In other words "Hello World" is a pointer to the character 'H' .
Once a reference variable has been defined to refer to a particular variable it can refer to any other variable. A reference is not a constant pointer.
The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.
Pointer literal (C++11) The only pointer literal is the nullptr keyword that is a prvalue of type std::nullptr_t . A prvalue of this type is a null pointer constant that can be converted to any pointer type, pointer-to-member type, or bool type. Parent topic: Literals.
It isn't correct because the string literal is not a pointer. It is an array. The literal does implicitly convert to a pointer to the first element of the array (just like all arrays do), but that result of the conversion is an rvalue. And an lvalue reference to non-const cannot be bound to an rvalue.
There is simply no reason to write that. There is no advantage to adding unnecessary indirection. const char* text = "Hello, World\n";
is simpler, and correct.
What the compiler is telling you is that you need a constant pointer.
Your construct is a reference to pointer to const char, so the pointer must also be constant.
You can't bind a temporary to a non-const reference unless it's also const.
const char *const &text = "Hello, World\n";
You could even do:
char* const& text = "Hello, World\n";
And it would probably compile in most compilers, but C++ standard does not allow for non const pointer to string literal for obvious safety reasons.
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