Probe and Modify Your Types' Alignment Programmatically

C++03 offers no portable mechanism for querying the alignment of a certain type, let alone overriding the default alignment. This vexing state of affairs is about to change with the addition of two new built-in operators to C++0x.

Your program needs to be able to determine the alignment of a certain type and tweak it if necessary. How do you do that without resorting to non-portable and risky hacks?

Use the new alignof and alignaskeywords to detect and modify the alignment of a given type.

Presenting the Problem Suppose you're writing a class that has to be used by various clients, each running on a different platform. The default alignment of your target machine is four bytes. However, some of your clients use 64-bit RISC architectures with a fundamental alignmentrequirement of 16 bytes:

A uniform alignment value for Session will ensure that every client will reconstruct a Sessionobject correctly from the same stream of bytes. A uniform alignment value will also enable you to serialize sessions into a file or store them in a remote database.

In C++03, the only way to ensure a uniform alignment value on every target platform is by using compilation flags and attributes. The problem is that compilation flags and attributes aren't portable, to say the least. Additionally, they complicate the deployment and maintenance of your apps, and clutter up your code.

Incompatible alignment values are a common problem. These lead to linkage errors (because the size of a class is encoded in its mangled name), or worse, runtime crashes and buffer overflows.

Two new keywords: alignas and alignofwere recently added to the C++0x standard. Let's see how you can use them to control the alignment of Session.