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?

Therhang
  • 825
  • 1
  • 9
  • 15
  • What about using `std::string`'s fill constructor and then accessing memory using `.data()`? – Aidan Gomez Sep 26 '15 at 00:39
  • I feel `std::unique_ptr` is rather more restrictive and harder to use than a `std::vector`. Not least of which is that the *vector* stores the *length* of the data. – Galik Sep 26 '15 at 01:26

0 Answers0