4

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?

1
  • "MB somebody know another container implementation for char array with which I can do that?" std::vector<char>... Commented Feb 10, 2012 at 22:27

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It does not work I got a fatal error from my application when I did that.
@itun : Then you're obviously using one of those non-C++11 implementations I referred to. ;-]
I know I use the last MinGW without C++11 support flag.
3

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

7 Comments

You mean value instead of required. But it won't work. the std::string's buffer is read-only.
+1 but I guess you mean instead of passing value into the function.
@MrLister A string is not read only, unless it is declared as const. The conversion from &s[0] to char* is fine.
Hm, I'll have to do some serious testing and internet searching.
Yes, I meant value, wasn't concentrating sorry.
|
2

You shouldn't. std::strings were 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.

Comments

0

You're gonna have to copy it to a string. AFAIK std::string does not let you access it's internals directory to do any sort of an address based direct assignment.

std::string s(charArry);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.