名稱空間
變體
操作

alignof 運算子 (C++11 起)

來自 cppreference.com
< cpp‎ | 語言
 
 
C++ 語言
 
 

查詢型別的對齊要求。

目錄

[編輯] 語法

alignof( type-id )

返回 std::size_t 型別的值。

[編輯] 解釋

返回 對齊方式,以位元組為單位,它是由 type-id 指示的任何型別例項所需的。此型別可以是完整物件型別、元素型別完整的陣列型別,或對這些型別之一的引用型別。

如果型別是引用型別,則此運算子返回引用型別的對齊方式;如果型別是陣列型別,則返回元素型別的對齊要求。

[編輯] 注意

關於 alignof 返回值的含義和屬性,請參閱對齊

[編輯] 關鍵詞

alignof

[編輯] 示例

#include <iostream>
 
struct Foo
{
    int   i;
    float f;
    char  c;
};
 
// Note: alignas(alignof(long double)) below can be
// simplified to alignas(long double) if desired.
struct alignas(alignof(long double)) Foo2
{
    // put your definition here
}; 
 
struct Empty {};
 
struct alignas(64) Empty64 {};
 
#define SHOW(expr) std::cout << #expr << " = " << (expr) << '\n'
 
int main()
{
    SHOW(alignof(char));
    SHOW(alignof(int*));
    SHOW(alignof(Foo));
    SHOW(alignof(Foo2));
    SHOW(alignof(Empty));
    SHOW(alignof(Empty64));
}

可能的輸出

alignof(char) = 1
alignof(int*) = 8
alignof(Foo) = 4
alignof(Foo2) = 16
alignof(Empty) = 1
alignof(Empty64) = 64

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
CWG 1305 C++11 type-id 不能表示對元素型別完整但邊界未知的陣列的引用
但元素型別完整
允許

[編輯] 參考文獻

  • C++23 標準 (ISO/IEC 14882:2024)
  • 7.6.2.6 Alignof [expr.alignof]
  • C++20 標準 (ISO/IEC 14882:2020)
  • 7.6.2.5 Alignof [expr.alignof]
  • C++17 標準 (ISO/IEC 14882:2017)
  • 8.3.6 Alignof [expr.alignof]
  • C++14 標準 (ISO/IEC 14882:2014)
  • 5.3.6 Alignof [expr.alignof]
  • C++11 標準 (ISO/IEC 14882:2011)
  • 5.3.6 Alignof [expr.alignof]

[編輯] 另請參閱

對齊要求 限制物件可以分配的地址
alignas (C++11) 指定變數的儲存應按特定量對齊
(說明符)[編輯]
獲取型別的對齊要求
(類模板) [編輯]
C 文件 用於 _Alignof, alignof 運算子