Move constructor for std::string from char*

后端 未结 4 1134
离开以前
离开以前 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:58

    std::string will make a copy of the null terminated string argument and manage that copy. There's no way to have it take ownership of a string you pass to it. So what you're doing is correct, the only improvement I'd suggest is a check for nullptr, assuming that is a valid return value for f(). This is necessary because the std::string constructor taking a char const * requires that the argument point to a valid array, and not be nullptr.

    char* cstring = f();
    std::string s(cstring ? cstring : "");
    delete[] cstring;   // You most likely want delete[] and not delete
    

    Now, if you don't need all of std::string's interface, or if avoiding the copy is important, then you can use a unique_ptr to manage the string instead.

    std::unique_ptr s{f()}; // will call delete[] automatically
    

    You can get access to the managed char * via s.get() and the string will be deleted when s goes out of scope.

    Even if you go with the first option, I'd suggest storing the return value of f() in a unique_ptr before passing it to the std::string constructor. That way if the construction throws, the returned string will still be deleted.

提交回复
热议问题