将构造函数std :: string从char * [英] Move constructor for std::string from char*
问题描述
我有一个函数 f
返回一个 char *
。函数文档说:
I have a function f
returning a char*
. The function documentation says:
The user must delete returned string
我想从它构造一个 std :: string
。要做的小事是:
I want to construct a std::string
from it. The trivial things to do is:
char* cstring = f();
std::string s(cstring);
delete cstring;
是否可以使用C ++功能做得更好?我想写如下
Is it possibile to do it better using C++ features? I would like to write something like
std::string(cstring)
避免泄露。
推荐答案
std :: string
将创建一个空终止字符串参数的副本,并管理该副本。没有办法让它拥有你传递给它的字符串的所有权。所以你正在做的是正确的,唯一的改进我建议是检查 nullptr
,假设是一个有效的返回值 f ()
。这是必要的,因为使用 char const *
的 std :: string
构造函数要求参数指向有效的数组,而不是 nullptr
。
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
现在,如果你不需要所有 std :: string
的接口,或者如果避免副本很重要,那么可以使用 unique_ptr
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<char[]> s{f()}; // will call delete[] automatically
您可以访问托管 char * 通过
s.get()
,字符串将 delete
code> s
You can get access to the managed char *
via s.get()
and the string will be delete
d when s
goes out of scope.
即使你使用第一个选项,我建议存储返回值在传递给 std :: string
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.
这篇关于将构造函数std :: string从char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!