I think this is a slight weakness of C ++. There is an unsuccessful combination of two factors:
- A function return is valid only as long as its argument is absent.
- Implicit conversion means that a function argument is not an object that it might seem to be.
I have no sympathy for people who do not think about the life of objects to which they have pointers / links. But the implicit conversion, which is certainly a language function with subtle pros and cons, does not make the analysis very easy here. Implicit conversion is sometimes bad news, so the explicit keyword exists. But the problem is not that converting to string bad at all, it is just bad for this function used in this wrong way.
The author of the function can actually disable the implicit conversion by defining overload:
const char *fun(const char *s) { return s; }
This change in itself means that code that was previously bad is working. Therefore, I think it is a good idea to do this in this case. Of course, this does not help if someone defines a type that fun has never heard of, and which has operator std::string() . In addition, fun not a realistic function, and for more useful routines, you may not want to provide an equivalent that works on char* . In this case, void fun(const char *); at least forces the caller to explicitly point to the string, which may help them use this function correctly.
Alternatively, the caller may notice that he provides a char* and returns a reference to string . It seems to me that this is a free lunch, so alarm clocks should call where this line comes from and how long it will last.
Steve jessop
source share