First, whether const reference or value doesn't change anything.
You then have to consider what the function is expecting. There
are different things which a function can do with a char*
or
a char const*
---the original versions of memcpy
, for
example, used these types, and it's possible that there is still
such code around. It is, hopefully, rare, and in the following,
I will assume that the char*
in the C function refer to '\0'
terminated strings.
If the C function takes a char const*
, you can pass it the
results of std::string::c_str()
; if it takes a char*
, it
depends. If it takes a char*
simply because it dates from the
pre-const
days of C, and in fact, it modifies nothing,
std::string::c_str()
followed by a const_cast
is
appropriate. If the C function is using the char*
as an out
parameter, however, things become more difficult. I personally
prefer declaring a char[]
buffer, passing this, and then
converting the results to std::string
, but all known
implementations of std::string
use a contiguous buffer, and
the next version of the standard will require it, so correctly
dimensioning the std::string
first (using
std::string::resize()
, then passing &s[0]
, and afterwards
redimensionning the string to the resulting length (determined
using strlen(s.c_str())
, if necessary) can also be used.
Finally (but this is also an issue for C programs using
char[]
), you have to consider any lifetime issues. Most
functions taking char*
or char const*
simply use the
pointer, and forget it, but if the function saves the pointer
somewhere, for later use, the string object must live at least
as long, and its size should not be modified during that period.
(Again, in such cases, I prefer using a char[]
.)