我想overalign緩存邊界上我喜歡的類型,所以我用alignas
:alignas用關鍵字not尊重
struct alignas(64) W { };
編譯沒有問題。不過,出乎我的意料,當我嘗試分配一堆W
S,他們不是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';
}
}
產量:
0 250
16 250
32 250
48 250
上幾個編譯(gcc 4.8.2,gcc 5.2.0,clang 3.7.1)。這是怎麼回事?我告訴它調整,爲什麼不調整?
[「這是執行定義是否支持過度對齊類型(\ [basic.align \])。」](http://eel.is/c++draft/expr.new#1)。另見[CWG issue 2130](http://wg21.link/cwg2130)。 –
@ T.C。這看起來應該是一個答案。 – NathanOliver
@ T.C。我怎麼知道一個實現是否支持它(顯然gcc和clang都沒有) – Barry