Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a reference of type "std::string&" (not const-qualified) cannot be initialized

Tags:

c++

string

When I try to compile the following function I get the error.

string& foo(){
return "Hello World";
}


Error:
1   IntelliSense: a reference of type "std::string &" (not const-qualified) cannot be initialized with a value of type "const char [12]"
like image 367
wayfare Avatar asked May 25 '11 15:05

wayfare


People also ask

Does c++ pass string by reference?

References in C++ are simply passed with the normal "pass-by-value" syntax: startup(filename) takes filename by reference.

What is the difference between a C++ string and an std::string?

There is no functionality difference between string and std::string because they're the same type.

Is std::string contiguous?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array.


1 Answers

There are two problems with your code. First, "Hello World!" is a char const[13], not an std::string. So the compiler has to (implicitly) convert it to an std::string. The result of a conversion is a temporary (rvalue in C++-speak), and you cannot initialize a reference to a non-const with a temporary. The second is that even if you could (or you declared the function to return a reference to const), you're returning a reference to something which will immediately go out of scope (and thus be destructed); any use of the resulting reference will result in undefined behavior.

The real question is: why the reference? Unless you're actually referring to something in an object with a longer lifetime, with the intent that the client code modify it (usually not a good idea, but there are notable exceptions, like operator[] of a vector), you should return by value.

like image 125
James Kanze Avatar answered Sep 29 '22 16:09

James Kanze