boost::asio
's various read
and write
functions and methods accept boost::asio::buffer
. According to buffer's documentation, a mutable std::string
cannot be wrapped in boost::asio::buffer
, and thus cannot be used for asio's read
functions. This is probably due to the fact that std::string
does not allow mutable access to its internal buffer (this was discussed previously here).
This is a shame, because std::string
is a convenient way to represent mutable buffers of data in C++. Without it, we're either left with POD arrays, boost::array
and std::vector<char>
. The first two are inconvenient with variable-length messages. std::vector<char>
can work, but it's an unnatural way to carry buffers of data around (*)
Questions:
- Are there other alternatives to
std::string
withboost::asio
for reading buffers? Am I missing something here? - I wonder why
std::vector<char>
is supported in a mutable buffer. Is it because it guarantees its internal buffer is contiguous in memory and allows mutable access to it with&vec[0]
?
Thanks in advance
(*) IMHO. Look at protobuf
serialization for instance - it offers serialization into std::string
but not into std::vector<char>
, at least not explicitly.
EDIT: I ended up using vector<char>
after all. protobuf
allows serialization into a vector<char>
by means of the SerializeToArray
call which takes a pointer (&vec[0]
can be passed there).