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:
- It allows fast assignment via
assignand fast direct access viadatathat is not allowed withvector<byte> - It allows easier memory management and const references, unlike using
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_casts)
std::strings 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::stringmay not be thread safe. The potential advantage ofstd::stringis easy concatenation, however, this can also be easily achieved using STL.Also, all those problems in relation to protocols dissapear when using
boost::asioand it’s buffer objects.As for drawbacks of
std::vector:std::swapPersonally I use
std::vectorfor variable sized arrays, andboost::arrayfor static sized ones.