Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a std::string directly from a char* array without copying?

Tags:

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

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.

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).

Is there some standard way to do this, or should I just write my own string class (ugh)? Thanks!

like image 382
fyhuang Avatar asked Jul 14 '11 22:07

fyhuang


People also ask

Can you assign a char array to a string?

You can also use string constructor to convert a char array to string. Pass the char array as argument to string constructor. This string will be initialized with the characters from char array.

How do I copy a Std string to a char array?

Using strcpy function The idea is to use the c_str() function to convert the std::string to a C-string. Then we can simply call the strcpy() function to copy the C-string into a char array.

How do I copy a char array to another?

strcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .


2 Answers

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.

For example:

std::string mystring;
mystring.resize(size);
WriteIntoArray(&mystring[0], size);
return mystring;

You may have to think carefully about a null terminator, however.

like image 83
John Calsbeek Avatar answered Oct 18 '22 23:10

John Calsbeek


You may implement your own std::allocator that instead of allocating new memory for your string, uses as the source the region you already have instantiated.

You should then instantiate your std::string using your allocator.

http://www.codeproject.com/Articles/4795/C-Standard-Allocator-An-Introduction-and-Implement

like image 32
Arturo Avatar answered Oct 18 '22 23:10

Arturo