c++ - What to watch out for when converting a std::string to a char* for C function? -


i have read many posts asking question on how convert c++ std::string or const std::string& char* pass c function , seems there quite few caveat's in regards doing this. 1 has beware string being contiguous , lot of other things. point i've never understood points 1 needs aware of , why?

i wondered if sum caveats , downfalls doing conversion std::string char* needed pass c function?

this when std::string const reference , when it's non-const reference, , when c function alter char* , when not alter it.

first, whether const reference or value doesn't change anything.

you have consider function expecting. there different things function can char* or char const*---the original versions of memcpy, example, used these types, , it's possible there still such code around. is, hopefully, rare, , in following, assume char* in c function refer '\0' terminated strings.

if c function takes char const*, can pass results of std::string::c_str(); if takes char*, depends. if takes char* because dates pre-const days of c, , in fact, modifies nothing, std::string::c_str() followed const_cast appropriate. if c function using char* out parameter, however, things become more difficult. prefer declaring char[] buffer, passing this, , converting results std::string, known implementations of std::string use contiguous buffer, , next version of standard require it, correctly dimensioning std::string first (using std::string::resize(), passing &s[0], , afterwards redimensionning string resulting length (determined using strlen(s.c_str()), if necessary) can used.

finally (but issue c programs using char[]), have consider lifetime issues. functions taking char* or char const* use pointer, , forget it, if function saves pointer somewhere, later use, string object must live @ least long, , size should not modified during period. (again, in such cases, prefer using char[].)


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -