How to put char array in std :: string

I allocate a char array, then I need to return it as a string, but I do not want to copy this char array, and then free it.

char* value = new char[required]; f(name, required, value, NULL); // fill the array strResult->assign(value, required); delete [] value; 

I do not want to do this above. I need to put the array directly into the std string container. How can i do this?

Edit1:

I realized that I should not and that the line is not intended for this purpose. MB does someone know another container implementation for char array with which i can do this?

+4
source share
4 answers

You should not. std::strings were not intended to display their internal data, which will be used as a buffer.
He did not guarantee that the address of the line buffer would not change during the execution of an external function, especially if the function does not allocate or free memory. And this does not guarantee that the string buffer is contiguous.

See, for example, here .

An example in your post is the best way to do this.

+2
source

In C ++ 11, work is guaranteed:

 std::string strResult(required, '\0'); f(name, required, &strResult[0], NULL); // optionally, to remove the extraneous trailing NUL (assuming f NUL-terminates): strResult.pop_back(); return strResult; 

In C ++ 03, which is not guaranteed to work, but it addresses the Library Issue 530 , which have been implemented in most standard library implementations for years, so it is probably safe, but ultimately depends on the implementation.

+5
source

Instead of passing value to the function, go to &s[0] , where s is the std::string right length.

+3
source

You will need to copy it to a string. AFAIK std :: string does not allow you to access its internal directory to perform any direct address assignment.

 std::string s(charArry); 
0
source

Source: https://habr.com/ru/post/1395832/


All Articles