Stack stack variables

Using the new C ++ 11 alignment tools, I wanted to make sure that the set of temporary (stack) variables would be on the same 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 does not allocate variables this way, so a will be on a different cache line than b and c .

Does this mean that the only way to correctly align multiple variables is through the 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

+6
source share
1 answer

To align multiple variables correctly, you must use an aggregate because the layout for automatic variables is not defined. I cannot find anything in the C ++ 11 standard, which states that variables with automatic storage should be allocated on the stack in the same order in which they are defined. Section 5.9 of the standard states that only a few types of pointer mappings are defined, and comparisons between variables with automatic storage do not apply to those that are specified.

+4
source

All Articles