alignas / alignof

Much more of my C++ programming seems to have been bits and bytes than is true of the general programming population, and I am pleased to see these two keywords introduced. In the new ISO standard, a good deal more is spelt out about the C++ memory model, and how it interoperates with your programming.

Consider the problem of needing to equate an array of bytes with some other type that is laid out over it. As an example, consider these two objects:

double d;
char array[sizeof(double)];
     

alignof is an operator that will tell you the byte-multiple for an object's memory location. Very often, this will be the word-size of the underlying hardware, and those of us who have been around since the 8088 microprocessor know that value will and does change.

alignas will change the alignment to something perhaps more coarse, but never finer.

Suppose that we are working on an antique 32-bit word machine. We would expect to find that:

alignof(array) == 4
     

Note that if array gets laid out on an odd word boundary, that the following statement might result in an ill formed program:

double * pd = static_cast<double *>(array); 
     

Need portability? If we know how we need the objects aligned, we can use an alignment specifier when we declare and define array.

alignas(double) char array[sizeof(double)];