Const-correctness in C++ is still giving me headaches. In working with some old C code, I find myself needing to assign turn a C++ string object into a C string and assign i
If you know that the std::string
is not going to change, a C-style cast will work.
std::string s("hello");
char *p = (char *)s.c_str();
Of course, p
is pointing to some buffer managed by the std::string
. If the std::string
goes out of scope or the buffer is changed (i.e., written to), p
will probably be invalid.
The safest thing to do would be to copy the string if refactoring the code is out of the question.