char*[]
object can be passed to function version2() & version 3() by the const reference, which means s2 is a temporary object equals to "###" or "@@@".
But why the temporary object s2 can be returned back, while the temporary object temp cannot.
int main()
{
result = version2(input, "###");
cout << "Your string enhanced: " << result << endl;
result = version3(input, "@@@");
cout << "Your string enhanced: " << result << endl;
return 0;
}
// No Error
const string & version2(string & s1, const string & s2)
{
return s2;
}
// Error
const string & version3(string & s1, const string & s2)
{
string temp = s2 + s1 + s2;
return temp;
}
The point is object life time.
For the 1st case, as you said, a temporary std::string
is created and passed to version2
(being bound to the parameter s2
). The temporary will be destroyed after the full-expression, i.e. the whole result = version2(input, "###");
. That means the reference returned by version2
remains valid, it's fine to use it for assigning to result
.
All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created,
For the 2nd case, a local object temp
is created inside version3
, it will be destroyed when get out of version3
. That means version3
will always return a dangled reference. And using it to assign to result
leads to UB. The compiler might give a diagnosis for it; but doesn't have to do.