I think it is a slight weakness of C++. There's an unfortunate combination of two factors:
- The function's return is only valid as long as its argument is.
- Implicit conversion means that the function's argument is not the object it may appear to be.
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 explicit
keyword exists. But the problem isn't that conversion to string
is 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:
const char *fun(const char *s) { return s; }
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 fun
has never heard of, and which has an operator std::string()
. Also, fun
is not a realistic function, and for more useful routines you might not want to provide an equivalent which operates on char*
. 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 a string
. 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.