0

I've ran into a few scenarios where I need to write a string to a temporary buffer, usually because that's just how the libraries I am using returns strings.

Examples typically look like (with vector):

std::vector<char> buffer(buffer_size);
getString(&buffer[0], buffer_size); //Or buffer.data()
std::string str(&buffer[0]);

But I prefer using (with unique_ptr):

std::unique_ptr<char[]> buffer(new char[buffer_size]);
getString(buffer.get(), buffer_size);
std::string str(buffer.get());

Since I see the first so often, I'm wondering if there's any benefit to using it instead. Which, if any, should be preferred?

2
  • What about using std::string's fill constructor and then accessing memory using .data()? Commented Sep 26, 2015 at 0:39
  • I feel std::unique_ptr<char[]> is rather more restrictive and harder to use than a std::vector<char>. Not least of which is that the vector stores the length of the data. Commented Sep 26, 2015 at 1:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.