alignas
지정자는 메모리에 있는 형식 또는 개체의 맞춤을 변경합니다.
구문
alignas(expression)
alignas(type-id)
alignas(pack...)
설명
, , union
class
또는 변수 선언에서 struct
지정자를 사용할 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
}