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]"
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are two problems with your code. First,
"Hello World!"is achar const[13], not anstd::string. So the compiler has to(implicitly) convert it to an
std::string. The result of aconversion 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 shouldreturn by value.