Namespaces
Variants

std:: aligned_union

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
aligned_union
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <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++标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 2979 C++11 未要求完整类型 要求完整类型

参见

获取类型的对齐要求
(类模板)
(since C++11) (deprecated in C++23)
定义适用于给定大小类型的未初始化存储的类型
(类模板)