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

前端 未结 13 1237
借酒劲吻你
借酒劲吻你 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:28

    in C++1x, this should work:

    foo(&s[0], s.size());
    

    However this needs a note of caution: The result of &s[0] (as the result of s.c_str(), BTW) is only guaranteed to be valid until any member function is invoked that might change the string. So you should not store the result of these operations anywhere. The safest is to be done with them at the end of the full expression, as my examples do.


    Pre C++-11 answer

    Since for to me inexplicable reasons nobody answered this the way I do now, and since other questions are now being closed pointing to this one, I'll add this here, even though coming a year too late will mean that it hangs at the very bottom of the pile...


    With C++03, std::string isn't guaranteed to store its characters in a contiguous piece of memory, and the result of c_str() doesn't need to point to the string's internal buffer, so the only way guaranteed to work is this:

    std::vector buffer(s.begin(), s.end());
    foo(&buffer[0], buffer.size());
    s.assign(buffer.begin(), buffer.end());
    

    This is no longer true in C++11.

提交回复
热议问题