Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string and data alignment

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.

like image 756
user416983 Avatar asked Sep 03 '25 05:09

user416983


1 Answers

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.

like image 79
user703016 Avatar answered Sep 04 '25 19:09

user703016