向量中元素的对齐分配

Aligned allocation of elements in vector

我需要让 std::vector 中的元素与内存中的某个给定步骤对齐。比如在程序中如下:

#include <vector>
#include <iostream>

struct __attribute__((aligned(256))) A
{
};

int main()
{
    std::vector<A> as(10);
    std::cout << &as[0] << std::endl;
    std::cout << &as[1] << std::endl;
}

我希望印刷号码的最后两位数字为“00”。

在实践中,我发现在 Visual Studio 2019 和 gcc 8+ 中确实如此。但是我可以绝对确定吗,还是只是巧合,std::vector(如 boost::alignment::aligned_allocator)中的一些自定义分配器是必要的?

In practice, I see that it is true in Visual Studio 2019, and in gcc 8+. But can I be absolutely sure, or is it just a coincidence and some custom allocator in std::vector (like boost::alignment::aligned_allocator) is necessary?

如果相应编译器的实现中没有错误(但是,如果需要,可以在汇编级别检查),没有理由期望如此。

从 C++11 开始,就有了 alignas-specifier which allows you to enforce the alignment in a standardized way. Consequently, the standard allocator will call operator new upon calling allocator::allocate(), to which it will forward the alignment information according to the documentation。因此,如果指定,标准分配器已经考虑了对齐需求。但是,当然,如果全局 operator new 被自定义实现重载,则无法做出此类保证。