he alignment requirement of your target platform is usually transparent. However, when you need to send or receive objects via a network connection, serialize objects, design heterogeneous containers, or construct different types of objects on a pre-determined memory address, there's no escape from poking into your compiler's alignment scheme. With the addition of alignment facilities to C++0x, probing and overriding the default alignment of your types becomes simpler, portable, and more intuitive.



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:

class Session //must have 16 byte alignment { long long timestamp; uid_t client_id; int authorizations; bool active; public: Session(); //... };

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.