首页 > 解决方案 > Aligned allocation of elements in vector

问题描述

I need to have elements in a std::vector aligned to some given step in memory. For example, in the program as follows:

#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;
}

I would expect that the last two digits in printed numbers will be ‘00’.

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++vectorboostmemory-alignment

解决方案


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?

There is no reason to expect that, provided the absence of bugs in the implementation of the respective compiler (which can however be checked on the assembly level, if required).

Since C++11, there is the 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. Thus, the standard allocator already respects alignment needs, if specified. However, of course if the global operator new is overloaded by a custom implementation, no such guarantee can be made.


推荐阅读