名稱空間
變體
操作

std::aligned_union

來自 cppreference.com
< cpp‎ | 型別
 
 
超程式設計庫
型別特性
型別類別
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型別屬性
(C++11)
(C++11)
(C++14)
(C++11)(C++26 中已棄用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已棄用)
(C++11)
型別特性常量
元函式
(C++17)
支援的操作
關係與屬性查詢
型別修改
(C++11)(C++11)(C++11)
型別轉換
(C++11)(C++23 中已棄用)
aligned_union
(C++11)(C++23 中已棄用)
(C++11)
(C++11)(直到 C++20*)(C++17)

(C++11)
(C++17)
編譯時有理數算術
編譯時整數序列
 
定義於標頭檔案 <type_traits>
template< std::size_t Len, class... Types >
struct aligned_union;
(C++11 起)
(C++23 中已棄用)

提供巢狀型別 type,它是一個平凡的標準佈局型別,其大小和對齊方式適用於作為未初始化儲存空間,用於儲存 Types 中列出的任何型別的物件。儲存空間的大小至少為 Lenstd::aligned_union 還會確定所有 Types 中最嚴格(最大)的對齊要求,並將其作為常量 alignment_value 提供。

如果 sizeof...(Types) == 0Types 中的任何型別不是完整的物件型別,則行為未定義。

是否支援任何擴充套件對齊是實現定義的。

如果程式為 std::aligned_union 新增特化,則行為未定義。

目錄

[編輯] 成員型別

名稱 定義
型別 一個平凡的標準佈局型別,適用於儲存 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 中最嚴格的對齊要求
(public static 成員常量)

[編輯] 可能的實現

#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 不需要完整型別 要求完整型別

[編輯] 另請參閱

獲取型別的對齊要求
(類模板) [編輯]
(自 C++11)(C++23 中已棄用)
定義適合用作給定大小型別的未初始化儲存的型別
(類模板) [編輯]