Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put char array into std::string

Tags:

c++

string

std

I allocate a char array then I need to return it as a string, but I don't want to copy this char array and then release its memory.

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

I don't want to do like above. I need put the array right in the std string container. How I can do that?

Edit1:

I understood that I should not and that the string is not designed for this purpose. MB somebody know another container implementation for char array with which I can do that?

like image 276
itun Avatar asked Dec 28 '22 06:12

itun


2 Answers

In C++11, the following is guaranteed to work:

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 that's not guaranteed to work, but it is addressed by Library Issue 530 which most standard library implementations have had implemented for years, so it's probably safe, but ultimately is implementation-dependent.

like image 59
ildjarn Avatar answered Dec 30 '22 10:12

ildjarn


Instead of passing value into the function, pass in &s[0], where s is a std::string of the right length.

like image 33
Stuart Golodetz Avatar answered Dec 30 '22 11:12

Stuart Golodetz