alignof(char) == 1?
sizeof(char) is always 1 and it seems to me that the alignment requirement of a type can never be larger than its size. Quoting from the upcoming C++11 standard (3.11):
An aligment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.
So i开发者_运维百科f the alignment of a type were greater than its size, it would not be possible to create arrays without empty space between consecutive elements.
Is this interpretation correct and is thus alignof(char) == 1 always?
You are correct.
You can infer from the "compact" (no padding) layout of C++ arrays that any object type such that an array of this type can be defined must have an alignment that is a divisor of its size.
In particular, the alignment of such a type of size 1 must be 1.
In particular, the alignment of char
, signed char
, and unsigned char
is 1.
OTOH, you cannot infer anything about the alignment of an abstract class with this argument.
I looked at the way C++11 defines pointer arithmetic and didn't see anything that would prevent a type's alignment from being larger than its size. The compiler would be responsible for making sure every element in the array was properly aligned (by inserting the right amount of padding) and for making sure that pointer arithmetic works properly. Basically, pointer arithmetic is not defined with reference to sizeof(*ptr) even though people usually talk about it as though it is.
n3290 § 5.7 p5:
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression.
edit:
However, the sizeof
operator is defined in terms of the offset between consecutive elements in an array, so alignof(X)
can't be greater than sizeof(X)
because that would mean an array of X contains objects at invalid alignments. At the same time, sizeof(X)
doesn't necessarily represent the actual size of the object. E.g. an X member or base sub-object of another type may use less than sizeof(X)
bytes to store, although I don't know of any implementation that actually uses that.
精彩评论