开发者

Pointer alignment

开发者 https://www.devze.com 2022-12-12 19:25 出处:网络
could anyone explain (by giving appropiate link for example) what does pointer alignment in c++ 开发者_StackOverflow社区means?

could anyone explain (by giving appropiate link for example) what does pointer alignment in c++ 开发者_StackOverflow社区means? Thank you.


This is a good one too - Data_structure_alignment

A memory address a, is said to be n-byte aligned when n is a power of two and a is a multiple of n bytes. In this context a byte is the smallest unit of memory access, i.e. each memory address specifies a different byte. An n-byte aligned address would have log2 n least-significant zeros when expressed in binary.


In C, pointers align on machine word boundaries in structs. So, even though you have:

typedef struct {
int a;
char c;
float f;
} example;

your sizeof will be different dependent upon your architecture. (each of 'a', 'c' and 'f' will be located on the aforementioned boundary and so will take potentially more space than just the size of an int, a character and a float.


Why you should bother: In performance critical areas with lots of memory reads and writes you can gain a lot of additional performance by minding propery pointer alignment. This is even more true when you are planning to use vector instructions such as MMX, SSE and the like.

You do not need to bother about it though when writing your regular code. Only once you have identified a bottleneck that has to do with lots memory access operations you should start to investigate this further.

0

精彩评论

暂无评论...
验证码 换一张
取 消