I know why the following does not work correclty, so I am not asking why. But I am feeling bad about it is that it seems to me that it is a very big programming hindrance.
#include <iostream>
#include <string>
using namespace std;
string ss("hello");
const string& fun(const string& s) {
return s;
}
int main(){
const string& s = fun("hello");
cout<<s<<endl;
cout<<fun("hello")<<endl;
}
The first cout will not work. the second cout will.
My concern is the following:
Is it not possible to imagine a situation where a method implementor wants to return an argument that is a const reference and is unavoidable?
I think it is perfectly possible.
What would you do in C++ in this situation?
Thanks.
I think it is a slight weakness of C++. There’s an unfortunate combination of two factors:
I have no sympathy for people who fail to think about the lifetime of objects they have pointers/references to. But the implicit conversion, which certainly is a language feature with subtle pros and cons, is not making the analysis very easy here. Sometimes implicit conversion is bad news, which why the
explicitkeyword exists. But the problem isn’t that conversion tostringis bad in general, it’s just bad for this function, used in this incorrect way.The author of the function can in effect disable implicit conversion, by defining an overload:
That change alone means the code which previously was bad, works. So I think it’s a good idea in this case to do that. Of course it doesn’t help if someone defines a type which the author of
funhas never heard of, and which has anoperator std::string(). Also,funis not a realistic function, and for more useful routines you might not want to provide an equivalent which operates onchar*. In that case,void fun(const char *);at least forces the caller to explicitly cast to string, which might help them use the function correctly.Alternatively, the caller could note that he’s providing a
char*, and getting back a reference to astring. That appears to me to be a free lunch, so alarm bells should be ringing where this string came from, and how long it’s going to last.