Alignof (char) == 1?

sizeof (char) is always 1, and it seems to me that the type alignment requirement can never be larger than its size. Quote from the upcoming C ++ 11 standard (3.11):

An aligment is an integer integer value defined by the implementation that represents the number of bytes between consecutive addresses on which this object can be allocated.

So, if the alignment of the type was larger than its size, it would be impossible to create arrays without empty space between consecutive elements.

Is this interpretation correct and thus aligns (char) == 1 always?

+6
source share
2 answers

You're right.

You can conclude from the "compact" layout (without filling) C ++ arrays that any type of object for which an array of this type can be defined must have an alignment that divides its size.

In particular, alignment of this type of size 1 should be 1.

In particular, the alignment of char , signed char and unsigned char is 1.

OTOH, you cannot conclude that the abstract class is aligned with this argument.

+1
source

I looked at how C ++ 11 determines pointer arithmetic and does not see anything that would prevent type alignment from being larger than its size. The compiler will be responsible for ensuring that each element of the array is correctly aligned (by inserting the correct number of indents) and to ensure the correct operation of pointer arithmetic. Basically, pointer arithmetic is not defined with reference to sizeof (* ptr), even if people usually talk about it as if it were.

n3290 ยง 5.7 p5:

When an expression that has an integral type is added or subtracted from the pointer, the result is the type of the operand of the pointer. If the pointer operand points to an element of the array object and the array is large enough, the result indicates the offset of the element from the original element, so that the difference between the indices of the resulting and initial elements of the array is equal to the integral expression.

edit:

However, the sizeof operator is defined in terms of the offset between consecutive elements in the array, therefore alignof(X) cannot be larger than sizeof(X) , because this means that the array from X contains objects with invalid alignments, At the same time, sizeof(X) does not necessarily represent the actual size of the object. For instance. An X element or base sub-object of another type may use less sizeof(X) bytes for storage, although I do not know any implementation that actually uses this.

0
source

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


All Articles