简体   繁体   English

如何创建char / std :: byte的std :: vector,其中第一个字节与16个字节对齐,但是没有填充?

[英]How to create std::vector of char/std::byte where first byte is aligned to 16 byes, but there is no padding?

There is an existing question that requires C++03 and has no answer, so I will open a new one. 有一个问题需要C ++ 03并且没有答案,所以我将打开一个新问题。

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. 我遇到的问题是我想要std::vectorstd::byte ,但是.data() (数据数组的第一个元素)是16字节对齐的。

alignas on wrapped char does not help because I do not want to have alignment gaps in the array. 包装char上的alignas没有帮助,因为我不想在数组中有对齐间隙。 In other words I want to keey alignment of 1 for elements, but I want alignment of 16 for the array. 换句话说,我想对元素进行1对齐,但我希望对齐数组16。

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. 如果有任何TBB或增强矢量可以做我想要的那样也会很棒。

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. 做对齐的最佳方法是使用boost的aligned_allocator

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). 从C ++ 17开始,它可以使用对齐的new (参见std::aligned_val_t重载)。 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. 您可以这样做,但可能需要花费大量时间才能正确完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM