名前空間
変種
操作

sizeof 演算子

提供: cppreference.com
< cpp‎ | language
 
 
C++言語
一般的なトピック
フロー制御
条件付き実行文
繰り返し文 (ループ)
ジャンプ文
関数
関数宣言
ラムダ関数宣言
inline 指定子
例外指定 (C++20未満)
noexcept 指定子 (C++11)
例外
名前空間
指定子
decltype (C++11)
auto (C++11)
alignas (C++11)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点
文字 - 文字列 - nullptr (C++11)
ユーザ定義 (C++11)
ユーティリティ
属性 (C++11)
typedef 宣言
型エイリアス宣言 (C++11)
キャスト
暗黙の変換 - 明示的な変換
static_cast - dynamic_cast
const_cast - reinterpret_cast
メモリ確保
クラス
クラス固有の関数特性
特別なメンバ関数
テンプレート
その他
 
 

オブジェクトまたは型のサイズを問い合わせます。

オブジェクトの実際のサイズを知る必要があるときに使用されます。

目次

[編集] 構文

sizeof( type ) (1)
sizeof expression (2)

どちらのバージョンも std::size_t 型の定数式です。

[編集] 説明

1) typeオブジェクト表現のバイト単位のサイズを返します。
2) 評価された場合の expression の型のオブジェクト表現のバイト単位のサイズを返します。

[編集] ノート

コンピュータアーキテクチャによっては、バイトは8ビットより大きいかもしれません。 正確な値は CHAR_BIT で取得できます。

sizeof(char)sizeof(char8_t)sizeof(signed char) および sizeof(unsigned char) は常に 1 と等しくなります。

sizeof は関数型、不完全型、またはビットフィールドの glvalue で使用することはできません。

参照型に適用されたときは、結果はその参照先の型のサイズです��

クラス型に適用されたときは、結果はそのオブジェクトのサイズに配列内でそのようなオブジェクトを配置するために要求される追加のパディングを加えたものになります。

sizeof は必ず非ゼロの値を返します (たとえ空のクラス型に適用された場合でも)。

式に適用されたときは、 sizeofその式を評価しません。 たとえその式が多相オブジェクトを指す場合でも、結果はその式の静的な型のサイズです。 左辺値から右辺値、配列からポインタ、関数からポインタへの変換は行われません。 しかし、 prvalue の引数に対する一時具体化は (形式的には) 行われます。 sizeof はその結果のオブジェクトのサイズを調べます。 (C++17以上)

[編集] キーワード

sizeof

[編集]

出力例はポインタが64ビットでintが32ビットのシステムのものです。

#include <iostream>
 
struct Empty {};
struct Base { int a; };
struct Derived : Base { int b; };
struct Bit { unsigned bit: 1; };
 
int main()
{
    Empty e;
    Derived d;
    Base& b = d;
    [[maybe_unused]] Bit bit;
    int a[10];
    std::cout << "size of empty class:              " << sizeof e        << "\n"
              << "size of pointer:                  " << sizeof &e       << "\n"
//            << "size of function:                "  << sizeof(void())  << "\n" // エラー
//            << "size of incomplete type:         "  << sizeof(int[])   << "\n" // エラー
//            << "size of bit field:               "  << sizeof bit.bit  << "\n" // エラー
              << "size of array of 10 int:         "  << sizeof(int[10]) << "\n"
              << "size of array of 10 int (2):     "  << sizeof a        << "\n"
              << "length of array of 10 int:       "  << ((sizeof a) / (sizeof *a)) << "\n"
              << "length of array of 10 int (2):   "  << ((sizeof a) / (sizeof a[0])) << "\n"
              << "size of the Derived:              " << sizeof d        << "\n"
              << "size of the Derived through Base: " << sizeof b        << "\n";
 
}

出力例:

size of empty class:              1
size of pointer:                  8
size of array of 10 int:         40
size of array of 10 int (2):     40
length of array of 10 int:       10
length of array of 10 int (2):   10
size of the Derived:              8
size of the Derived through Base: 4

[編集] 関連項目