Reputation: 35654
Google's Protocol buffer uses the C++ standard string class std::string
as variable size byte array (see here) similar to Python where the string class is also used as byte array (at least until Python 3.0).
This approach seems to be good:
assign
and fast direct access via data
that is not allowed with vector<byte>
byte*
.But I am curious: Is that the preferred way for a byte arrays in C++? What are the drawbacks of this approach (more than a few static_cast
s)
Upvotes: 18
Views: 17076
Reputation: 57615
std::string
s may have a reference counted implementation which may or may not be a advantage/disadvantage to what you're writing -- always be careful about that. std::string
may not be thread safe. The potential advantage of std::string
is easy concatenation, however, this can also be easily achieved using STL.
Also, all those problems in relation to protocols dissapear when using boost::asio
and it's buffer objects.
As for drawbacks of std::vector
:
std::swap
Personally I use std::vector
for variable sized arrays, and boost::array
for static sized ones.
Upvotes: 3
Reputation: 32685
Personally, I prefer std::vector
, since std::string
is not guaranteed to be stored contiguously and std::string::data()
need not be O(1). std::vector
will have data
member function in C++0x.
Upvotes: 8
Reputation: 96889
I "think" that using std::vector
is a better approach, because it was intended to be used as an array. It is true that all implementations(I know and heard of) store string "elements" in contiguous memory, but that doesn't make it standard. i.e. the code that uses std::string
like a byte array, it assumes that the elements are contiguous where they don't have to be according to the standards.
Upvotes: 2