C++: Correct implementation for passing a std::string to a C function that wants to change the string?

Viewed 3794

I have a function in a third-party library written in C: char* fix_filename_slashes(char* path). This function expects a mutable C-string passed to it so it can change all the slashes in the path to the correct use based on the operating system. All the strings I'm using in my Facade are declared as std::strings. I attempted to simply use foo.c_str() as every other function that expects a C string doesn't change it and expects a const char *, but this function causes an error: Error: Argument of type "const char *" is incompatible with parameter of type "char *"

Is the result I came up with:

char* tempf = const_cast<char*>(filename.c_str());
filename = std::string(fix_filename_slashes(tempf));
tempf = NULL;

considered "correct" or are there other (more correct?) ways to accomplish the task?

EDIT

Whups. Apparently the function returns a COPY of the string. Still there are some nice answers already given.

5 Answers
Related