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

型のアライメント要件を問い合わせます。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - HTMLタグ、属性、
タグ内のテキストは翻訳していません
- C++固有の用語(Syntax、Explanation、Notes、Keywords、Example、Defect reports、References、See also)は原文のまま保持しました
- 数値や書式設定は完全に保持されています

構文

alignof( type-id )

std::size_t 型の値を返します。

説明

the alignment で示される、 type-id によって指定された型の任意のインスタンスに必要なアラインメントをバイト単位で返します。 type-id は、 complete オブジェクト型、要素型がcompleteである配列型、またはそれらの型への参照型のいずれかです。

型が参照型の場合、演算子は参照先の型のアラインメントを返します。型が配列型の場合、要素型のアラインメント要件が返されます。

注記

alignment が返す値の意味と特性については、 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++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
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ドキュメント for _Alignof , alignof operator