alignas (C++)

指定子は alignas 、メモリ内の型またはオブジェクトの配置を変更します。

構文

alignas(expression)
alignas(type-id)
alignas(pack...)

解説

指定子は、変数宣言、またはunion変数宣言でclassstruct使用alignasできます。

の場合 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 が適用されている場合は、最大値を持つ宣言が使用されます。 alignas値は0無視されます。

次の例は、ユーザー定義型で使用 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
}

関連項目

#pragma pack
位置合わせ
alignof
コンパイラ エラー C2023
コンパイラ警告 C4359