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?
You shouldn’t.
std::stringswere not designed to expose their internal data to be used as a buffer.It’s not guaranteed that the string’s buffer address won’t change during execution of an external function, especially not if the function allocates or deallocates memory itself.
And it’s not guaranteed that the string’s buffer is contiguous.
See, for example, here.
The example in your post is the better way to do it.