I'm planning to use std::string
as a generic data buffer (instead of roll my own). I need to pack all kinds of POD into it, including user defined structs, is the memory buffer allocated by std::string
properly aligned for such purpose ?
If it's unspecified in C++ standard, what's the situation in libstdc++ ?
The host CPU is x86_64.
First of all, std::string
is probably not the best container to use if what you want to do is store arbitrary data. I'd suggest using std::vector
instead.
Second, the alignment of all allocations made by the container is controlled by its allocator (the second template parameter, which defaults to std::allocator<T>
). The default allocator will align allocations on the size of the largest standard type, which is often long long
or long double
, respectively 8 and 16 bytes on my machine, but the size of these types is not mandated by the standard.
If you want a specific alignment you should either check what your compiler aligns on, or ask for alignment explicitly, by supplying your own allocator or using std::aligned_storage
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With