alignas
指定子は、メモリ内の型またはオブジェクトの配置を変更します。
構文
alignas(expression)
alignas(type-id)
alignas(pack...)
解説
alignas
指定子は、struct
、class
、union
、または変数宣言で使用できます。
alignas(expression)
の場合、式は 0 または 2 の累乗 (1,2, 4, 8, 16, ...) の整数定数式である必要があります。他のすべての式の形式が正しくありません。
コードの移植性を__declspec(align(#))
の代わりにalignas
を使用します。
alignas
の一般的な用途は、次の例に示すように、ユーザー定義型の配置を制御します。
struct alignas(8) S1
{
int x;
};
static_assert(alignof(S1) == 8, "alignof(S1) should be 8");
同じ宣言に複数の alignas
が適用されている場合は、最大値を持つものが使用されます。 0
のalignas
値は無視されます。
次の例は、ユーザー定義型で alignas
を使用する方法を示しています。
class alignas(4) alignas(16) C1 {};
// `alignas(0)` ignored
union alignas(0) U1
{
int i;
float f;
};
union U2
{
int i;
float f;
};
static_assert(alignof(C1) == 16, "alignof(C1) should be 16");
static_assert(alignof(U1) == alignof(U2), "alignof(U1) should be equivalent to alignof(U2)");
配置値として型を指定できます。 次の例に示すように、型の既定の配置が配置値として使用されます。
struct alignas(double) S2
{
int x;
};
static_assert(alignof(S2) == alignof(double), "alignof(S2) should be equivalent to alignof(double)");
配置値には、テンプレート パラメーター パック (alignas (pack...)
) を使用できます。 パック内のすべての要素の最大アライメント値が使用されます。
template <typename... Ts>
class alignas(Ts...) C2
{
char c;
};
static_assert(alignof(C2<>) == 1, "alignof(C2<>) should be 1");
static_assert(alignof(C2<short, int>) == 4, "alignof(C2<short, int>) should be 4");
static_assert(alignof(C2<int, float, double>) == 8, "alignof(C2<int, float, double>) should be 8");
複数の alignas
が適用されている場合、結果の配置はすべての alignas
値の中で最も大きく、適用される型の自然な配置より小さくすることはできません。
ユーザー定義型の宣言と定義は、同じアラインメント値を持つ必要があります。
// Declaration of `C3`
class alignas(16) C3;
// Definition of `C3` with differing alignment value
class alignas(32) C3 {}; // Error: C2023 'C3': Alignment (32) different from prior declaration (16)
int main()
{
alignas(2) int x; // ill-formed because the natural alignment of int is 4
}