C ++ `std :: string` -like container with 4 byte aligned buffer

I need a data structure in C ++ that acts like a standard byte container, but flattens a buffer with a multiplicity of four bytes. I would like to reuse standard library abstractions as much as possible, rather than rolling back my own abstraction.

So far I have used std::stringand std::vector<std::uint8_t>for this purpose. Unfortunately, I have error reports on the latest Mac OS, where it apparently string::data()no longer aligns to 4 bytes, but rather matches the address matching 1 mod 4. As soon as I saw this, I realized, of course, nothing in The specification ensures that strings are aligned by 4 bytes. I could switch to vector<char>, but, unfortunately, now I'm not sure why this should be aligned to 4 bytes. Potentially, even with the help of a special allocator, the implementation vectorcould do something strange at the beginning of the buffer allocated to it.

My question is: what is a simple way to get a container with dynamic size of single-byte objects from the C ++ standard library, in which the first byte is on a 4-byte aligned address, and individual bytes can be obtained through operator[]?

Note that this is not the same as asking how to ensure that the allocator used by the container returns 4-byte aligned memory. For example, it std::stringstill allocates 4-byte aligned memory (maybe 8, actually), it's just that on Mac OS it string::data()doesn't indicate the beginning of the allocated buffer. I do not see anything in the specification that would prevent it from vector<char>doing the same, even if at the moment it works.

+4
source share
1 answer

std::vector<uint32_t> , data() unsigned char * .

+1

Source: https://habr.com/ru/post/1693378/


All Articles