I need a data structure in C++ that acts like a standard container of bytes but aligns the buffer at a multiple of four bytes. I'd like to re-use standard library abstractions as much as possible, rather than rolling my own abstraction.
Until now, I had been using std::string
and std::vector<std::uint8_t>
for this purpose. Unfortunately, I've gotten bug reports on the latest Mac OS, where apparently string::data()
is no longer 4-byte aligned, but rather rather at an address congruent to 1 mod 4. As soon as I saw this, I realized of course nothing in the spec guarantees strings will be 4-byte aligned. I could switch over to vector<char>
, but unfortunately now I'm not sure why this should be 4-byte aligned. Potentially even with a custom allocator the vector
implementation could do something strange at the beginning of the buffer it allocates.
My question: What is a simple way of getting a dynamically-sized container of single-byte objects from the C++ standard library in which the first byte is at a 4-byte aligned address and individual bytes can be accessed through operator[]
?
Note that this is not the same thing as asking how to ensure that the allocator used by the container returns 4-byte aligned memory. For example, std::string
still allocates 4-byte aligned memory (probably 8, actually), it's just that on Mac OS string::data()
does not point to the start of the allocated buffer. I don't see anything in the spec that would prevent a vector<char>
from doing the same thing, even though for now that seems to work.