Namespaces
Variants

alignof operator (since C++11)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

查询类型的对齐要求。

目录

语法

alignof( 类型标识 )

返回类型为 std::size_t 的值。

说明

返回由 类型标识 所指示类型(该类型可以是 完整 对象类型、元素类型为完整的数组类型,或指向这些类型的引用类型)的任何实例所需的 对齐 量,以字节为单位。

如果类型是引用类型,该运算符返回被引用类型的对齐要求;如果类型是数组类型,则返回元素类型的对齐要求。

注释

请参阅 对齐 了解 alignof 返回值的含义及属性。

关键词

alignof

示例

#include <iostream>
struct Foo
{
    int   i;
    float f;
    char  c;
};
// 注意:下面的 alignas(alignof(long double)) 可以简化为 alignas(long double)
struct alignas(alignof(long double)) Foo2
{
    // 在此处填入定义
}; 
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 运算符