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.
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!
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With