Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying boost::array<char> to std::string

I am trying to cvopy boost::array<char> to std::string.

boost::array<char, 1024> _buffer;
std::string data;
std::copy(_buffer.begin(), _buffer.begin()+bytes_transferred, data.begin());

which is not working. So I changed it a little bit.

char _buffer[1024];
std::string data;
std::copy(_buffer, _buffer+bytes_transferred, data.begin());

second one is not working either.

like image 385
Dipro Sen Avatar asked Jun 14 '12 19:06

Dipro Sen


2 Answers

The issue here is that copy assumes that space already exists for the data you're writing; it doesn't create any new room for you. Consequently, both of the above pieces of code cause undefined behavior, since you're going to be copying characters to a location where space hasn't previously been reserved.

The best way to do this would be to use the string constructor:

boost::array<char, 1024> _buffer;
std::string data(_buffer.begin(), _buffer.end());

or

char _buffer[1024];
std::string data(_buffer, _buffer + 1024);

This will initialize the string as a copy of the data stored in the array.

Hope this helps!

like image 89
templatetypedef Avatar answered Oct 11 '22 14:10

templatetypedef


You can use back_insert_iterator. Assigning to it will call push_back function of the underlying container so you don't need to worry with allocating space manually.

std::copy(_buffer.begin(), _buffer.begin()+bytes_transferred, std::back_inserter(data));
like image 37
jrok Avatar answered Oct 11 '22 12:10

jrok