I write the following code:
const string& combine(string &s1,string &s2)
{
return s1+s2;
}
but when I pass two strings to this function, the result I use "std::cout" to print is the empty string.I don’t know what the reason is.
Thanks in advance.
>Solution :
The behaviour of your code is undefined. This is because s1 + s2 is an anonymous temporary and you are attempting to bind that to a reference return type.
The output you observe is a manifestation of that undefined behaviour.
Changing the return type of the function to a std::string value is a fix.
Another more interesting fix perhaps is to return one of the input strings modified, so the reference propagates back to the caller. See
#include <iostream>
#include <string>
const std::string& combine(std::string &s1, const std::string &s2)
{
return s1 += s2;
}
int main() {
std::string s1 = "Hello";
std::cout << combine(s1, ", World!");
}
The introduction of const allows ", World!" to bind to s2.
In general, writing a function that returns a reference can cause unexpected issues. The C++ standard library function std::max is a well-known example: if one of the parameters is an anonymous temporary and that value is selected then you have a possibility of a dangling reference! Usually they are confined to returning class member variables (usually bound to a const reference).