...

/

Alignment: The .alignof Property

Alignment: The .alignof Property

Understand the working of the .alignof property.

We'll cover the following...

By default, every object is placed at memory locations that are multiples of an amount specific to the type of that object. That amount is called the alignment of that type. For example, the alignment of int is 4 because int variables are placed at memory locations that are multiples of 4 (4, 8, 12, etc.).

Alignment is needed for CPU performance or requirements because accessing misaligned memory addresses can be slower or cause a bus error. In addition, certain types of variables only work properly at aligned addresses.

The .alignof property

The .alignof property of a type is its default alignment value. For classes, .alignof is the alignment of the class variable, not the class object. The alignment of a class object is obtained by std.traits.classInstanceAlignment.

The following program prints the alignments of various types:

Press + to interact
import std.stdio;
import std.meta;
import std.traits;
struct EmptyStruct {
}
struct Struct {
char c;
double d;
}
class EmptyClass {
}
class Class {
char c;
}
void main() {
alias Types = AliasSeq!(char, short, int, long,
double, real,
string, int[int], int*,
EmptyStruct, Struct,
EmptyClass, Class);
writeln(" Size Alignment Type\n",
"=========================");
foreach (Type; Types) {
static if (is (Type == class)) {
size_t size = __traits(classInstanceSize, Type);
size_t alignment = classInstanceAlignment!Type;
} else {
size_t size = Type.sizeof;
size_t alignment = Type.alignof;
}
writefln("%4s%8s %s",
size, alignment, Type.stringof);
}
}

The output of the program may be different in different environments.

Later, you will see how variables can be constructed (emplaced) at specific memory locations. For correctness and efficiency, objects must be constructed at addresses that match their alignments.

Let’s consider two consecutive objects of the Class type above, which are 17 bytes each. Although 0 is not a legal address for a variable on most platforms, to simplify the example let’s ...