c++pointersreferenceconstantsconst-pointer

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?


Solution

  • 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