4

There is an existing question that requires C++03 and has no answer, so I will open a new one.

Problem I have is that I want to have std::vector of std::byte, but so that .data()(first element of data array) is 16 byte aligned.

alignas on wrapped char does not help because I do not want to have alignment gaps in the array. In other words I want to keey alignment of 1 for elements, but I want alignment of 16 for the array.

Ideally I would like to avoid using a custom allocator. If there is any TBB or boost vector that does what I want that would be also great.

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

1 Answers1

4

Aligning the data in a vector ain't provided by default. Not even for aligned classes.

The best way of doing alignment is with the aligned_allocator of boost.

Unfortunately, it doesn't prevent padding, it even overallocates to adapt the pointer on the alignment. From C++17, it can used aligned new (see std::aligned_val_t overloads). However, all implementations I've seen actually use the same trick.

An alternative is allocating a whole page at once, and do your own memory management with a custom allocator. You can do it, though it might take a lot of time to do correctly.

JVApen
  • 11,008
  • 5
  • 31
  • 67