I have a function that manipulates a string, and I need it to work on both C-style strings, and C++ std::string:
// C-style overload
void TransformString(const char *in_c_string, char *out_string);
// C++ std::strings overload
std::string TransformString(const std::string &in_string);
In order to avoid redundant code, I can implement the actual algorithm in only one of them, and then have the other call it. So, if put the implementation in the C++ overloaded function, then the C-style function will look like:
void TransformString(const char *in_c_string, char * out_c_string) {
std::string in_string(in_c_string);
std::string out_string = TransformString(in_string); // call C++ std::string overload
strcpy(out_c_string, out_string.c_str()); // unwanted memory copy
}
My question is: Can I do this (having the algorithm implemented in only one function) without the extra copy (from std::string
internal buffer to the C-style string)? My first thought was to try and "steal" the buffer, like a string move constructor does, but upon searching the web it looks like there is no safe way to do this, as it is implementation specific. And if I write the algorithm in the C-style function, the problem is the same as in the C++ function I have to allocate space for the char*
string, and then move it to the std::string
object.
I must mention that I do not know the size of the resulting string before the transformation is completed.
Thank you.
EDIT
The size of the buffer is not a problem here (I know the max size and the function receives an allocated buffer). I cannot just return the std::string.c_str() because then the buffer would become invalidated when the std::string object would be destroyed (just after the return would occur). I have changed the name of the variable out_c_string. (thanks 0x499602D2)