如何直接从char *数组创建一个std :: string而不复制? [英] How to create a std::string directly from a char* array without copying?
问题描述
假设我有一个字符数组,我已经在堆上分配,我想将其转换为std :: string。目前我正在做以下事情:
Say I have an array of chars, which I have allocated on the heap, and which I want to convert into an std::string. Currently I am doing the following:
char *array = new char[size];
WriteIntoArray(array, size);
std::string mystring(array);
delete[] array;
return mystring; // or whatever
根据我在互联网上阅读的内容(http://www.cplusplus.com / reference / string / string / string /),字符串构造函数执行我传递的缓冲区的副本,让我释放缓冲区(稍后,字符串释放它的内部缓冲区)。我想要做的是分配我的缓冲区,将它的传输控制到字符串,然后让它释放我的缓冲区,当它被破坏。
From what I read on the internet (http://www.cplusplus.com/reference/string/string/string/), the string constructor performs a copy of the buffer I pass it, leaving me to free the buffer (later, the string frees its internal buffer). What I would like to do is to allocate my buffer, transfer control of it to the string, and then have it free my buffer when it is destructed.
问题<一个href =http://stackoverflow.com/questions/361500/initializing-stdstring-from-char-without-copy>初始化std :: string从char *无副本看起来有希望,但我的代码依赖在上面的例子中的API调用(WriteIntoArray),它必须写入一个字符数组,所以我必须创建一个C风格的char *缓冲区,不能转换我的代码只使用内置的字符串操作
The question initializing std::string from char* without copy looked promising, but my code relies on API calls ("WriteIntoArray" in the above example) which have to write into an array of chars, so I have to create a C-style char* buffer, and cannot convert my code to use only built-in string operations (which was the answer suggested).
有没有一些标准的方法来做到这一点,还是我应该写自己的字符串类(ugh)?谢谢!
Is there some standard way to do this, or should I just write my own string class (ugh)? Thanks!
推荐答案
如果你使用一个符合C ++ 0x的实现或许多C ++库中的一个,存储为 std :: string
,那么你可以得到一个 char *
直接指向你的 std :: string
。
If you're using a conforming C++0x implementation, or one of the many C++ libraries that guarantee contiguous storage for std::string
, then you can get a char*
that points directly to the storage used by your std::string
.
例如:
std::string mystring;
mystring.resize(size);
WriteIntoArray(&mystring[0], size);
return mystring;
然而,您可能必须仔细考虑一个空终止符。
You may have to think carefully about a null terminator, however.
这篇关于如何直接从char *数组创建一个std :: string而不复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!