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)];
Last updated 2014-07-19T15:44:11+00:00.
Links to the standard
A discussion of the alignment is found in section 7.6.2.
Benefits
It is much easier to write truly portable code across hardware platforms.
Risks
There appear to be none. Many programmers will never use these two keywords in their own code.