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

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

    If you can afford extra allocation, instead of a recommended strcpy I would consider using std::vector<char> like this:

    // suppose you have your string:
    std::string some_string("hello world");
    // you can make a vector from it like this:
    std::vector<char> some_buffer(some_string.begin(), some_string.end());
    // suppose your C function is declared like this:
    // some_c_function(char *buffer);
    // you can just pass this vector to it like this:
    some_c_function(&some_buffer[0]);
    // if that function wants a buffer size as well,
    // just give it some_buffer.size()
    

    To me this is a bit more of a C++ way than strcpy. Take a look at Meyers' Effective STL Item 16 for a much nicer explanation than I could ever provide.

    0 讨论(0)
提交回复
热议问题