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]"
References in C++ are simply passed with the normal "pass-by-value" syntax: startup(filename) takes filename by reference.
There is no functionality difference between string and std::string because they're the same type.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With