Before modern C++ the only way to align variables or structures on a given byte boundary was to inject padding; to align a

struct
to 16 bytes you had to do this:

struct Old
{
	int x;
	char padding[16 - sizeof(int)];
};

Not any more! Modern C++ introduced a keyword just for that:

alignas
(read more about it here). Now you can specify struct’s alignment like this:

struct alignas(16) New
{
	int x;
};

This can be of great help when dealing with constructive or destructive interference of L1 cache lines. You can also space local variables apart, as well as struct/class members. Here’s a complete example (alignas.cpp):

#include 

using namespace std;

int main()
{
	struct Old
	{
		int x;
		char padding[16 - sizeof(int)];
	};
	cout << "sizeof(Old): " << sizeof(Old) << endl << endl;

	struct alignas(16) New
	{
		int x;
	};
	cout << "sizeof(New): " << sizeof(New) << endl << endl;

	alignas(16) int x{}, y{};
	alignas(16) int z{};
	ptrdiff_t delta1 = (uint8_t*)&y - (uint8_t*)&x;
	ptrdiff_t delta2 = (uint8_t*)&z - (uint8_t*)&y;
	cout << "Address of 'x'      : " << &x << endl;
	cout << "Address of 'y'      : " << &y << endl;
	cout << "Address of 'z'      : " << &z << endl;
	cout << "Distance 'x' to 'y' : " << delta1 << endl;
	cout << "Distance 'y' to 'z' : " << delta2 << endl << endl;

	struct             Empty   {};
	struct alignas(64) Empty64 {};

	cout << "sizeof(Empty)  : " << sizeof(Empty)   << endl;
	cout << "sizeof(Empty64): " << sizeof(Empty64) << endl << endl;

	struct Full
	{
		alignas(32) char c;
		alignas(16) int x, y;
	};
	cout << "sizeof(Full): " << sizeof(Full) << endl << endl;
}

sizeof(Old): 16
sizeof(New): 16
Address of 'x'      : 0x7ffee4a448c0
Address of 'y'      : 0x7ffee4a448d0
Address of 'z'      : 0x7ffee4a448e0
Distance 'x' to 'y' : 16
Distance 'y' to 'z' : 16
sizeof(Empty)  : 1
sizeof(Empty64): 64
sizeof(Full): 64

Program output.

7 Replies to “Data alignment the C++ way”

  1. if i recall my white book correctly, int x:0 would cause the next field to be aligned on an int boundary.

Leave a Reply to AnonymousCancel reply