types_aligned_union
types_aligned_union (정렬된 공용체)
std::aligned_union은 C++11에서 도입된 타입 특성(type trait)으로, 주어진 여러 타입들을 저장할 수 있는 초기화되지 않은 메모리 공간으로 사용하기 적합한 타입을 제공해요. 이 템플릿은 저장 공간의 크기와 정렬 요구 사항을 자동으로 계산해 주며, C++23부터는 더 이상 사용되지 않아요(deprecated). 여기서는 이 타입의 정의, 멤버, 사용 예시를 자세히 살펴볼게요.
출처: cppreference
본문
정의
<type_traits> 헤더에 정의되어 있어요.
| 정의 | |
|---|---|
template < std::size_t Len, class... Types > struct aligned_union; |
(C++11 이후) (C++23에서 deprecated) |
이 구조체는 중첩 타입 type을 제공해요. type은 Types에 나열된 임의의 객체를 위한 초기화되지 않은 저장 공간으로 사용하기에 적합한 크기와 정렬을 가진 사소한(trivial) 표준 레이아웃 타입이에요. 저장 공간의 크기는 최소 Len 이상이에요. 또한 std::aligned_union은 모든 Types 중에서 가장 엄격한(가장 큰) 정렬 요구 사항을 결정하여 상수 alignment_value로 제공해요.
만약 sizeof...(Types) == 0이거나 Types 중 어떤 타입이 완전한 객체 타입(complete object type)이 아니라면, 동작은 정의되지 않아요(undefined behavior).
확장 정렬(extended alignment)이 지원되는지 여부는 구현에 따라 정의돼요.
프로그램이 std::aligned_union에 대한 특수화를 추가하면 동작이 정의되지 않아요.
멤버 타입
| 이름 | 정의 |
|---|---|
type |
Types의 모든 타입을 저장하기에 적합한 사소하고 표준 레이아웃인 타입 |
헬퍼 타입
| 정의 | |
|---|---|
template < std::size_t Len, class... Types > using aligned_union_t = typename aligned_union<Len, Types...>::type; |
(C++14 이후) (C++23에서 deprecated) |
멤버 상수
| 이름 | 설명 |
|---|---|
alignment_value [static] |
모든 Types의 가장 엄격한 정렬 요구 사항 (공용 정적 멤버 상수) |
가능한 구현
#include <algorithm>
template < std::size_t Len, class... Types >
struct aligned_union {
static constexpr std::size_t alignment_value = std::max({ alignof(Types)... });
struct type {
alignas(alignment_value) char _s[std::max({ Len, sizeof(Types)... })];
};
};
예제
#include <iostream>
#include <string>
#include <type_traits>
int main()
{
std::cout << sizeof(std::aligned_union_t<0, char>) << ' ' // 1
<< sizeof(std::aligned_union_t<2, char>) << ' ' // 2
<< sizeof(std::aligned_union_t<2, char[3]>) << ' ' // 3 (!)
<< sizeof(std::aligned_union_t<3, char[4]>) << ' ' // 4
<< sizeof(std::aligned_union_t<1, char, int, double>) << ' ' // 8
<< sizeof(std::aligned_union_t<12, char, int, double>) << '\n'; // 16 (!)
using var_t = std::aligned_union<16, int, std::string>;
std::cout << "var_t::alignment_value = " << var_t::alignment_value << '\n'
<< "sizeof(var_t::type) = " << sizeof(var_t::type) << '\n';
var_t::type aligned_storage;
int* int_ptr = new(&aligned_storage) int(42); // placement new
std::cout << "*int_ptr = " << *int_ptr << '\n';
std::string* string_ptr = new(&aligned_storage) std::string("bar");
std::cout << "*string_ptr = " << *string_ptr << '\n';
*string_ptr = "baz";
std::cout << "*string_ptr = " << *string_ptr << '\n';
string_ptr->~basic_string();
}
가능한 출력:
1 2 3 4 8 16
var_t::alignment_value = 8
sizeof(var_t::type) = 32
*int_ptr = 42
*string_ptr = bar
*string_ptr = baz
결함 보고서
다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.
| DR | 적용 대상 | 발표된 동작 | 올바른 동작 |
|---|---|---|---|
| LWG 2979 | C++11 | 완전한 타입이 요구되지 않았음 | 완전한 타입을 요구함 |
같이 보기
alignment_of (C++11) |
타입의 정렬 요구 사항을 얻음 (클래스 템플릿) [편집] |
|---|---|
aligned_storage (C++11 이후) (C++23에서 deprecated) |
주어진 크기의 타입을 위한 초기화되지 않은 저장 공간으로 사용하기 적합한 타입을 정의함 (클래스 템플릿) [편집] |