Reputation: 19
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)
^
Upvotes: 0
Views: 93
Reputation: 12641
You can cast it to const reference.
foo((const char *&) s2);
Upvotes: 0
Reputation: 302932
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
Upvotes: 3