Can I get a non-const C string back from a C++ string?

前端 未结 13 1254
借酒劲吻你
借酒劲吻你 2020-12-01 15:33

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

13条回答
  •  不思量自难忘°
    2020-12-01 16:20

    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.

提交回复
热议问题