Move constructor for std::string from char*

后端 未结 4 1137
离开以前
离开以前 2021-01-12 05:13

I have a function f returning a char*. The function documentation says:

The user must delete returned string

I wa

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 05:55

    This code can never be correct:

    std::string s(cstring);
    delete cstring;
    

    The std::string constructor that takes a character pointer, requires a NUL-terminated string. So it is multiple characters.

    delete cstring is scalar delete.

    Either you are trying to create a string from a character scalar (in which case, why the indirection?)

    std::string s(cstring[0]);
    delete cstring;
    

    or you have multiple characters, and should delete accordingly

    std::string s(cstring);
    delete [] cstring;
    

    Check the other answers for the recommended way to make sure delete[] gets used, e.g.

    std::string(std::unique_ptr(f()).get())
    

提交回复
热议问题