Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can't Make a Reference To Pointer for Constant Assign a String Literal

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?

like image 627
Alan Jian Avatar asked Jun 22 '20 13:06

Alan Jian


People also ask

Is a string literal a pointer?

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' .

Are references constant pointers?

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.

Is it possible to modify a string literal?

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.

What is a pointer literal?

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.


2 Answers

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.

like image 102
eerorika Avatar answered Oct 08 '22 20:10

eerorika


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.

like image 35
anastaciu Avatar answered Oct 08 '22 21:10

anastaciu