Dipro Sen
Dipro Sen

Reputation: 4670

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.

Upvotes: 8

Views: 13894

Answers (2)

jrok
jrok

Reputation: 55395

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));

Upvotes: 5

templatetypedef
templatetypedef

Reputation: 372704

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!

Upvotes: 14

Related Questions