alignas
(C++)
規範 alignas
會變更記憶體中類型或物件的對齊方式。
語法
alignas(expression)
alignas(type-id)
alignas(pack...)
備註
您可以在 、class
、 union
或變數宣告上使用struct
alignas
規範。
針對 alignas(expression)
,表達式必須是 0 的整數常數運算式,或是 2 的冪(1、2、4、8、16、...)。所有其他表達式都是格式錯誤的。
使用 alignas
, __declspec(align(#))
而不是 用於程式代碼可移植性。
的常見用法 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
}
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應