C++ STL's String eqivalent for Binary Data

后端 未结 5 1726
北恋
北恋 2020-12-23 14:45

I am writing a C++ application and I was wondering what the C++ conventional way of storing a byte array in memory.

Is there something like a string, except specifi

5条回答
  •  情书的邮戳
    2020-12-23 15:08

    You should use std::vector or std::vector (if you have a modern stdint.h header). There's nothing wrong with using unsigned char[] or uint8_t[] if you are working with fixed size buffers. Where std::vector really shines is when you need to grow or append to your buffers frequently. STL iterators have the same semantics as pointers, so STL algorithms will work equally well with std::vector and plain old arrays.

    And as CAdaker pointed out, the expression &v[0] is guaranteed to give you the underlying pointer to the vector's buffer (and it's guaranteed to be one contiguous block of memory). This guarantee was added in an addendum to the C++ standard.

    Personally, I'd avoid using std::string to manipulate arbitrary byte buffers, since I think it's potentially confusing, but it's not an unheard of practice.

提交回复
热议问题