Why is alignment of char array always equal to 1?

I read a little about alignment in C ++, and I'm not sure why the alignment of a class containing only an element of the char array is not the sizeof of the array, but it always turns 1. For example

 #include <iostream> struct Foo{char m_[16];}; // shouldn't this have a 16 byte alignment?! int main() { std::cout << sizeof(Foo) << " " << alignof(Foo); } 

Live on coliru

in the above code it is clear that sizeof(Foo) is 16, however its alignment is 1, see the code output.

Why in this case alignof(Foo) 1? Please note: if I replaced char m_[16]; to a fundamental type of type int m_; , then alignof(Foo) will become what I would expect, i.e. sizeof(int) (on my machine it's 4).

The same thing happens if I simply declare an array char arr[16]; , then alignof(arr) will be 1.

+5
source share
1 answer

Note: data alignment is described in detail in this article . If you want to know what the term as a whole means and why this is an important issue, read the article.

Aligment is defined in C ++ as an integer value defined by the implementation, representing the number of bytes between consecutive addresses where this object can be allocated [6.11. 1] Alignment .

In addition, alignments must be non-negative integer powers of 2 [6.11.4] Alignment .

When we calculate the alignment of the structure, we must take into account one more rule [6.11.5] Alignment :

Alignments range from weaker to stronger or more rigorous alignments. Stricter alignments have higher alignment values. an address that satisfies the alignment requirement also satisfies any weaker correct alignment requirements.

It is not explicitly stated, but these rules imply that the alignment of the structure should be at least strictly the same as the alignment of its most strictly aligned element . It may be more, but it is not necessary, and usually it is not.

So, when the alignment of the structure from the OP example is decided, the alignment of the structure should be no less than the alignment of its only char[16] element type char[16] . Then 8.3.6 [expr.alignof] :

If alignment is applied to the reference type, the result is alignment of the reference type. When alignof is applied to the type array, the result is the alignment of the element type .

alignof(char[16]) is equal to alignof(char) , which will usually be 1 due to [6.11.6] Alignment :

(...) narrow character types should have the weakest alignment requirement.

In this example:

 struct Foo { char c[16]; double d; }; 

double has lowercase alignment than char , so alignof(Foo) is equal to alignof(double) .

+10
source

Source: https://habr.com/ru/post/1264864/


All Articles