简体   繁体   中英

Non-const reference to non-const pointer to const char

Why can't I take a reference to s2 in foo ? I'm compiling with gcc 5.1.0:

#include <cstring>

void foo(const char*& p)
{
    while (*p && *p <= '5')
        ++p;
}

int main()
{
    const char *s1 = "1234567890";
    char *s2 = new char[strlen(s1) + 1];
    strcpy(s2, s1);

    foo(s1);  // OK
    foo(s2);  // error

    return 0;
}

I compiled with:

$ g++ test_reference.cpp

The compiler gave me:

test_reference.cpp: In function ‘int main()’:
test_reference.cpp:16:11: error: invalid initialization of non-const reference of type ‘const char*&’ from an rvalue of type ‘const char*’
     foo(s2);  // error
           ^
test_reference.cpp:3:6: note:   initializing argument 1 of ‘void foo(const char*&)’
 void foo(const char*& p)
      ^

For simplicity, you are trying to do:

char* s = ...;
const char*& r = s;

The const here may be misleading. You would think this is equivalent to:

int i = 4;
const int& ri = i;

Which works. But these are not equivalent. ri here is a reference to a const type, but r is a reference to a pointer to const char , that is not a const type.

The ultimate issue is that char* and char const* are not reference-related (meaning that the types are either the same or in the same hierarchy). However, if your reference was a reference to a const type, it would work fine. That is:

const char* const& cr = s;

Basically, you can take an lvalue reference to a non-const type T only from a reference-related type or from a class that is convertible to a reference related type. But you can take an lvalue reference to a const type from a much wider source of expressions:

double d = 4.0;
int& ri = d;         // error: int, double aren't reference-related
const int& rci = d;  // OK

您可以将其转换为const引用。

foo((const char *&) s2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM