Using new C++11 alignment tools I wanted to make sure that a set of temporary (stack) variables will lie in one cache line. My first naive attempt was as follows:
int main() {
alignas(64) int a; // 0x7fffc58aac80, properly aligned at 64
int b; // 0x7fffc58aac7c
int c; // 0x7fffc58aac78
return 0;
}
Stupid me! Stack doesn't allocate the variables this way, thus a
will be on different cache line than b
and c
.
Does this mean that the only way to properly align several variables is through an aggregate?
struct alignas(64) Abc {
int x;
int y;
int z;
};
int main() {
Abc foo;
// x 0x7fff40c2d3c0 (aligned at 64)
// y 0x7fff40c2d3c4
// z 0x7fff40c2d3c8
return 0;
}
Compiler: Clang 3.2
To properly align several variables you must use an aggregate, because the layout for automatic variables is not defined. I can't find anything in the C++11 standard that says variables with automatic storage have to be allocated on the stack in the same order they are defined. Section 5.9 of the standard insists that only a few kinds of pointer comparisons are defined, and comparisons between variables with automatic storage is not among those listed as defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With