alignas关键字未得到尊重

Bar*_*rry 6 c++ c++11 alignas

我想在缓存边界上输入我的类型,所以我使用了alignas:

struct alignas(64) W { };
Run Code Online (Sandbox Code Playgroud)

编译好了.但是,令我惊讶的是,当我尝试分配一堆Ws时,它们不是64字节对齐但实际上是16字节对齐的:

#include <iostream>
#include <iomanip>
#include <unordered_map>

struct alignas(64) W { };

int main() {
    std::unordered_map<int, int> offset;

    for (int i = 0; i < 1000; ++i) {
        auto w = new W;
        offset[(uintptr_t)w % 64]++;
    }   

    for (const auto& p : offset) {
        std::cout << p.first << ' ' << p.second << '\n';
    }   
}
Run Code Online (Sandbox Code Playgroud)

产量:

0 250
16 250
32 250
48 250
Run Code Online (Sandbox Code Playgroud)

几个编译(gcc 4.8.2,gcc 5.2.0,clang 3.7.1).这是怎么回事?我告诉它要对齐,为什么不对齐?

ajn*_*neu 3

这在这里得到了很好的回答:https ://stackoverflow.com/a/16510895

基本上:(new至少在正常使用中)仅保证alignof(std::max_align_t)每次调用都有恒定的最大对齐()new