If I need a binary buffer object,
like that used for TCP/UDP communication,
what would I base it on, in c++ ?
-
vector<unsigned char>? -
std::string? — std::string can hold 0-bytes, contrary to popular belief, so it can be used to hold binary data -
new char[]? -
malloc()?
Did anybody see std::vector used for binary buffers ?
I did not see. Why ? Performance ?
And I did see malloc() often used for binary buffers.
In C++. Can anybody confirm ? Explain ?
Thanks
A binary buffer can be just seen as a piece of memory that you reserve for storing some unstructured information.
In this sense, using new
char[]andmallocare perfectly equivalent, IMO, in that they give you a piece of memory and a pointer to it.Using
std::vectoris a different matter; aside from the cost, which I don’t think is relevant since you will useto access the underlying buffer like you would do with
malloc, it has its advantages, like buffer extensibility and more access safety than a straight pointer; you might read the discussion here. I have used them in a project myself.std::strings have in principle the problem of the C++ (98, 03) standard not guaranteeing the contiguousness of the underlying buffer, but this does not seem to be an issue with compiler implementations. C++0x seems to have standardized buffer contiguousness (but I have not searched for that specifically). So you could also use them, but read before Herb Sutter’s comment here (it is not in the main article body, but in the third comment posted at the end of it).Anyway, between
std::stringandstd::vector, I would choosestd::vector.