Rather than modify the existing function, I'd just create an overload that acts as a wrapper. Assuming the existing function is ret_type f(char *)
, I'd write the overload something like:
ret_type f(std::string s) {
return f(&s[0]);
}
Note passing s
by value instead of reference, minimizing the effort expended to get a copy of the string.
In theory, this isn't guaranteed to work (i.e., a string's buffer isn't guaranteed to be contiguous) until C++03. In reality, that guarantee was fairly easy for the committee to add primarily because nobody knew of an implementation of std::string
that did anything else.
Likewise, it could theoretically be missing the NUL terminator. If you're concerned about that possibility you could use return f(const_cast<char *>(s.c_str()));
instead, or add an s.push_back('\0');
before the return:
ret_type f(std::string s) {
s.push_back('\0');
return f(&s[0]);
}