5

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?

anastaciu
  • 23,467
  • 7
  • 28
  • 53

3 Answers3

8

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
3

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
2

The conversion to a const char* can be seen as temporary returned by value. You can't bind a reference to a non-const temporary. To extend the life of a temporary you would have to make the pointer const too. If that's not an option, you'll have to bind the reference to a pointer that is not temporary.

Example:

#include <iostream>

int main() {
    const char* foo = "foo\n";
    const char* bar = "bar\n";
    const char*& text = foo;
    
    std::cout << text;
    foo = bar;
    std::cout << text;
}
foo
bar
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108