std::aligned_union
来自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 [静态] | 所有 Types 的最严格对齐 (公开静态成员常量) |
[编辑]可能的实现
#include <algorithm> template<std::size_t Len, class... Types>struct aligned_union {staticconstexprstd::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);// 原位 newstd::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++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2979 | C++11 | 不要求完整类型 | 要求完整类型 |
[编辑]参阅
(C++11) | 获取类型的对齐要求 (类模板) |
(C++11 起)(C++23 弃用) | 定义适于用作给定大小的类型的未初始化存储的类型 (类模板) |