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

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

    Is it really that difficult to do yourself?

    #include 
    #include 
    
    char *convert(std::string str)
    {
        size_t len = str.length();
        char *buf = new char[len + 1];
        memcpy(buf, str.data(), len);
        buf[len] = '\0';
        return buf;
    }
    
    char *convert(std::string str, char *buf, size_t len)
    {
        memcpy(buf, str.data(), len - 1);
        buf[len - 1] = '\0';
        return buf;
    }
    
    // A crazy template solution to avoid passing in the array length
    // but loses the ability to pass in a dynamically allocated buffer
    template 
    char *convert(std::string str, char (&buf)[len])
    {
        memcpy(buf, str.data(), len - 1);
        buf[len - 1] = '\0';
        return buf;
    }
    

    Usage:

    std::string str = "Hello";
    // Use buffer we've allocated
    char buf[10];
    convert(str, buf);
    // Use buffer allocated for us
    char *buf = convert(str);
    delete [] buf;
    // Use dynamic buffer of known length
    buf = new char[10];
    convert(str, buf, 10);
    delete [] buf;
    

提交回复
热议问题