I want to overalign my type on a cache boundary, so I used alignas
:
struct alignas(64) W { };
This compiles fine. But then, to my surprise, when I try to allocate a bunch of W
s, they're not 64-byte aligned but actually 16-byte aligned:
#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';
}
}
Yields:
0 250
16 250
32 250
48 250
on several compiles (gcc 4.8.2, gcc 5.2.0, clang 3.7.1). What's up? I told it to align, why isn't it aligning?
new
? If I create aW
on the stack, will it be guaranteed 64-bytes aligned? – Protamineoperator new
andoperator delete
insidestruct W
that callaligned_alloc
andaligned_free
internally without complicating the job for external clients – Balbur0 1000
– Citronellalalignof( W )
returns 64, i.e. the requested alignment rather than the actual one, 16. (gcc 5.2.1) – Multitude