std::aligned_union
From cppreference.com
| ヘッダ <type_traits> で定義 |
||
| template< std::size_t Len, class... Types > struct aligned_union; |
(C++11以降) (C++23で非推奨) |
|
ネストされた型typeを提供します。これは、Typesにリストされた型のいずれかのオブジェクトの未初期化ストレージとして使用するのに適したサイズとアライメントを持つ、自明な 標準レイアウト型です。ストレージのサイズは少なくともLenです。std::aligned_unionはまた、すべてのTypesの中で最も厳密な(最大の)アライメント要件を決定し、それを定数alignment_valueとして利用可能にします。
sizeof...(Types) == 0の場合、またはTypes内のいずれかの型が完全なオブジェクト型ではない場合、動作は未定義です。
拡張アライメントがサポートされているかどうかは、実装定義です。
プログラムが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で非推奨) |
|
[編集] メンバー定数
| 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 | 完全型は要求されていなかった | 完全型を要求する |
[編集] 関連項目
| (C++11) |
型のアライメント要件を取得する (クラステンプレート) |
| (C++11以降)(C++23で非推奨) |
与えられたサイズの型の未初期化ストレージとして使用するのに適した型を定義する (クラステンプレート) |